Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ts-sdk] Allow enums with no value, add a test for TransactionData BCS #1484

Merged
merged 20 commits into from
Apr 21, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[ts-sdk] Add tests
  • Loading branch information
666lcz committed Apr 12, 2022
commit 912c63cb3d19a048f6d31cb845bd8c3c1f96d453
4 changes: 3 additions & 1 deletion sdk/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@
},
"dependencies": {
"bn.js": "^5.2.0",
"tweetnacl": "^1.0.3"
"buffer": "^6.0.3",
"tweetnacl": "^1.0.3",
"util": "^0.12.4"
},
"resolutions": {
"tsdx/**/node-notifier": "10.0.0"
Expand Down
3 changes: 2 additions & 1 deletion sdk/typescript/src/cryptography/ed25519-keypair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import nacl from 'tweetnacl';
import { Base64DataBuffer } from '../serialization/base64';
import { Keypair } from './keypair';
import { PublicKey } from './publickey';
import { TextEncoder } from 'util';

/**
* Ed25519 Keypair data
Expand Down Expand Up @@ -86,7 +87,7 @@ export class Ed25519Keypair implements Keypair {
}

/**
* Returns the signature for the provided data.
* Return the signature for the provided data.
*/
signData(data: Base64DataBuffer): Base64DataBuffer {
return new Base64DataBuffer(
Expand Down
2 changes: 1 addition & 1 deletion sdk/typescript/src/cryptography/keypair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface Keypair {
getPublicKey(): PublicKey;

/**
* Returns the signature of the data
* Return the signature for the data
*/
signData(data: Base64DataBuffer): Base64DataBuffer;
}
17 changes: 6 additions & 11 deletions sdk/typescript/src/cryptography/publickey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ export class PublicKey {
this._bn = value._bn;
} else {
if (typeof value === 'string') {
this._bn = new BN(Buffer.from(value, 'base64'));
const buffer = Buffer.from(value, 'base64');
if (buffer.length !== 32) {
throw new Error(`Invalid public key input`);
}
this._bn = new BN(buffer);
} else {
this._bn = new BN(value);
}
Expand All @@ -55,11 +59,6 @@ export class PublicKey {
}
}

/**
* Default public key value.(All zeros)
*/
static default: PublicKey = new PublicKey(Buffer.alloc(PUBLIC_KEY_SIZE));

/**
* Checks if two publicKeys are equal
*/
Expand All @@ -71,11 +70,7 @@ export class PublicKey {
* Return the base-64 representation of the public key
*/
toBase64(): string {
return this._bn.toString(64);
}

toJSON(): string {
return this.toBase64();
return this.toBuffer().toString('base64');
}

/**
Expand Down
3 changes: 0 additions & 3 deletions sdk/typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ export * from './cryptography/ed25519-keypair';
export * from './cryptography/keypair';
export * from './cryptography/publickey';

export * from './providers/provider';
export * from './providers/json-rpc-provider';

export * from './serialization/base64';

export * from './signers/txn-data-serializers/rpc-txn-data-serializer';
Expand Down
38 changes: 0 additions & 38 deletions sdk/typescript/src/providers/json-rpc-provider.ts

This file was deleted.

33 changes: 0 additions & 33 deletions sdk/typescript/src/providers/provider.ts

This file was deleted.

9 changes: 1 addition & 8 deletions sdk/typescript/src/signers/raw-signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@
// SPDX-License-Identifier: Apache-2.0

import { Ed25519Keypair } from '../cryptography/ed25519-keypair';
import { Provider } from '../providers/provider';
import { Base64DataBuffer } from '../serialization/base64';
import { defineReadOnly } from '../utils/properties';
import { SignaturePubkeyPair, Signer } from './signer';

export class RawSigner extends Signer {
private readonly _keypair: Ed25519Keypair;

constructor(keypair: Ed25519Keypair, provider: Provider) {
constructor(keypair: Ed25519Keypair) {
super();
this._keypair = keypair;
defineReadOnly(this, 'provider', provider);
}

async getAddress(): Promise<string> {
Expand All @@ -26,8 +23,4 @@ export class RawSigner extends Signer {
pubKey: this._keypair.getPublicKey(),
};
}

connect(provider: Provider): Signer {
return new RawSigner(this._keypair, provider);
}
}
64 changes: 1 addition & 63 deletions sdk/typescript/src/signers/signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@
// SPDX-License-Identifier: Apache-2.0

import { PublicKey } from '../cryptography/publickey';
import { Provider, TransactionResponse } from '../providers/provider';
import { Base64DataBuffer } from '../serialization/base64';
import {
TransferTransaction,
TxnDataSerializer,
} from './txn-data-serializers/txn-data-serializer';
import { TxnDataSerializer } from './txn-data-serializers/txn-data-serializer';

///////////////////////////////
// Exported Types
Expand All @@ -23,7 +19,6 @@ export type SignaturePubkeyPair = {
///////////////////////////////
// Exported Abstracts
export abstract class Signer {
readonly provider?: Provider;
readonly serializer?: TxnDataSerializer;

///////////////////
Expand All @@ -36,61 +31,4 @@ export abstract class Signer {
* Returns the signature for the data and the public key of the signer
*/
abstract signData(data: Base64DataBuffer): Promise<SignaturePubkeyPair>;

// Returns a new instance of the Signer, connected to provider.
// This MAY throw if changing providers is not supported.
abstract connect(provider: Provider): Signer;

///////////////////
// Sub-classes MAY override these

/**
* Sign a transaction and submit to the Gateway for execution
*
* @param txBytes a Base64 string representation of BCS serialised TransactionData bytes
*/
async signAndExecuteTransaction(
txBytes: Base64DataBuffer
): Promise<TransactionResponse> {
this._checkProvider('signAndExecuteTransaction');
const sig = await this.signData(txBytes);
return await this.provider!.executeTransaction({
txBytes: txBytes.toString(),
signature: sig.signature.toString(),
pubKey: sig.pubKey.toString(),
});
}

/**
* Serialize and Sign a `Transfer` transaction and submit to the Gateway for execution
*/
async transfer(
transaction: TransferTransaction
): Promise<TransactionResponse> {
this._checkProviderAndSerializer('transfer');
const txBytes = await this.serializer!.new_transfer(transaction);
return await this.signAndExecuteTransaction(txBytes);
}

///////////////////
// Sub-classes SHOULD leave these alone

_checkProviderAndSerializer(operation?: string): void {
this._checkProvider(operation);
this._checkSerializer(operation);
}

_checkProvider(operation?: string): void {
if (!this.provider) {
throw new Error(`missing provider for ${operation || '_checkProvider'}`);
}
}

_checkSerializer(operation?: string): void {
if (!this.serializer) {
throw new Error(
`missing serializer for ${operation || '_checkSerializer'}`
);
}
}
}
65 changes: 65 additions & 0 deletions sdk/typescript/test/cryptography/ed25519-keypair.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

import nacl from 'tweetnacl';
import { Base64DataBuffer, Ed25519Keypair } from '../../src';
import { TextEncoder } from 'util';

const VALID_SECRET_KEY =
'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIg==';
const INVALID_SECRET_KEY =
'mdqVWeFekT7pqy5T49+tV12jO0m+ESW7ki4zSU9JiCgbL0kJbj5dvQ/PqcDAzZLZqzshVEs01d1KZdmLh4uZIG==';

describe('ed25519-keypair', () => {
it('new keypair', () => {
const keypair = new Ed25519Keypair();
expect(keypair.getPublicKey().toBytes().length).toBe(32);
expect(2).toEqual(2);
});

it('create keypair from secret key', () => {
const secretKey = Buffer.from(VALID_SECRET_KEY, 'base64');
const keypair = Ed25519Keypair.fromSecretKey(secretKey);
expect(keypair.getPublicKey().toBase64()).toEqual(
'Gy9JCW4+Xb0Pz6nAwM2S2as7IVRLNNXdSmXZi4eLmSI='
);
});

it('creating keypair from invalid secret key throws error', () => {
const secretKey = Buffer.from(INVALID_SECRET_KEY, 'base64');
expect(() => {
Ed25519Keypair.fromSecretKey(secretKey);
}).toThrow('provided secretKey is invalid');
});

it('creating keypair from invalid secret key succeeds if validation is skipped', () => {
const secretKey = Buffer.from(INVALID_SECRET_KEY, 'base64');
const keypair = Ed25519Keypair.fromSecretKey(secretKey, {
skipValidation: true,
});
expect(keypair.getPublicKey().toBase64()).toEqual(
'Gy9JCW4+Xb0Pz6nAwM2S2as7IVRLNNXdSmXZi4eLmSA='
);
});

it('generate keypair from random seed', () => {
const keypair = Ed25519Keypair.fromSeed(Uint8Array.from(Array(32).fill(8)));
expect(keypair.getPublicKey().toBase64()).toEqual(
'E5j2LG0aRXxRumpLXz29L2n8qTIWIY3ImX5Ba9F9k8o='
);
});

it('signature of data is valid', () => {
const keypair = new Ed25519Keypair();
const signData = new Base64DataBuffer(
new TextEncoder().encode('hello world')
);
const signature = keypair.signData(signData);
const isValid = nacl.sign.detached.verify(
signData.getData(),
signature.getData(),
keypair.getPublicKey().toBytes()
);
expect(isValid).toBeTruthy();
});
});
Loading