diff --git a/modules/bitgo/test/browser/browser.spec.ts b/modules/bitgo/test/browser/browser.spec.ts index 7a8a22f001b..ae98757f6fd 100644 --- a/modules/bitgo/test/browser/browser.spec.ts +++ b/modules/bitgo/test/browser/browser.spec.ts @@ -36,6 +36,8 @@ describe('Coins', () => { Tao: 1, Ttao: 1, AptToken: 1, + Icp: 1, + Ticp: 1, }; Object.keys(BitGoJS.Coin) .filter((coinName) => !excludedKeys[coinName]) diff --git a/modules/sdk-coin-icp/package.json b/modules/sdk-coin-icp/package.json index dede65d644d..b8e8496fe55 100644 --- a/modules/sdk-coin-icp/package.json +++ b/modules/sdk-coin-icp/package.json @@ -46,8 +46,12 @@ "@dfinity/agent": "^2.2.0", "@dfinity/candid": "^2.2.0", "@dfinity/principal": "^2.2.0", - "@noble/curves": "1.8.1", - "crc-32": "^1.2.2" + "bignumber.js": "^9.1.1", + "cbor-x": "^1.5.9", + "crc-32": "^1.2.0", + "js-sha256": "^0.9.0", + "protobufjs": "^7.2.5", + "@noble/curves": "1.8.1" }, "devDependencies": { "@bitgo/sdk-api": "^1.59.0", diff --git a/modules/sdk-coin-icp/src/lib/iface.ts b/modules/sdk-coin-icp/src/lib/iface.ts new file mode 100644 index 00000000000..c000585d2b0 --- /dev/null +++ b/modules/sdk-coin-icp/src/lib/iface.ts @@ -0,0 +1,185 @@ +import { + TransactionExplanation as BaseTransactionExplanation, + TransactionType as BitGoTransactionType, +} from '@bitgo/sdk-core'; + +export const REQUEST_STATUS = 'request_status'; + +export enum RequestType { + CALL = 'call', + READ_STATE = 'read_state', +} + +export enum SignatureType { + ECDSA = 'ecdsa', +} + +export enum CurveType { + SECP256K1 = 'secp256k1', +} + +export enum OperationType { + TRANSACTION = 'TRANSACTION', + FEE = 'FEE', +} + +export enum MethodName { + SEND_PB = 'send_pb', // send_pb is the method name for ICP transfer transaction +} + +export enum Network { + ID = '00000000000000020101', // ICP does not have different network IDs for mainnet and testnet +} + +export interface IcpTransactionData { + senderAddress: string; + receiverAddress: string; + amount: string; + fee: string; + senderPublicKeyHex: string; + memo: number | BigInt; // memo in string is not accepted by ICP chain. + transactionType: OperationType; + expiryTime: number | BigInt; +} + +export interface IcpPublicKey { + hex_bytes: string; + curve_type: string; +} + +export interface IcpAccount { + address: string; +} + +export interface IcpCurrency { + symbol: string; + decimals: number; +} + +export interface IcpAmount { + value: string; + currency: IcpCurrency; +} + +export interface IcpOperation { + type: string; + account: IcpAccount; + amount: IcpAmount; +} + +export interface IcpMetadata { + created_at_time: number; + memo: number | BigInt; // memo in string is not accepted by ICP chain. + ingress_start: number | BigInt; // it should be nano seconds + ingress_end: number | BigInt; // it should be nano seconds +} + +export interface IcpTransaction { + public_keys: IcpPublicKey[]; + operations: IcpOperation[]; + metadata: IcpMetadata; +} + +export interface IcpAccountIdentifier { + address: string; +} + +export interface SendArgs { + memo: { memo: number | BigInt }; + payment: { receiverGets: { e8s: number } }; + maxFee: { e8s: number }; + to: { hash: Buffer }; + createdAtTime: { timestampNanos: number }; +} + +export interface HttpCanisterUpdate { + canister_id: Uint8Array; + method_name: MethodName; + arg: Uint8Array; + sender: Uint8Array; + ingress_expiry: bigint; +} + +export interface SigningPayload { + account_identifier: IcpAccountIdentifier; + hex_bytes: string; + signature_type: SignatureType; +} + +export interface PayloadsData { + payloads: SigningPayload[]; + unsigned_transaction: string; +} + +export interface Signatures { + signing_payload: SigningPayload; + signature_type: SignatureType; + public_key: IcpPublicKey; + hex_bytes: string; +} + +export interface cborUnsignedTransaction { + updates: [string, HttpCanisterUpdate][]; + ingress_expiries: bigint[]; +} + +export interface ReadState { + sender: Uint8Array; + paths: Array<[Buffer, Buffer]>; + ingress_expiry: bigint; +} + +export interface UpdateEnvelope { + content: { + request_type: RequestType; + canister_id: Uint8Array; + method_name: MethodName; + arg: Uint8Array; + sender: Uint8Array; + ingress_expiry: bigint; + }; + sender_pubkey: Uint8Array; + sender_sig: Uint8Array; +} + +export interface ReadStateEnvelope { + content: ReadState & { + request_type: RequestType; + }; + sender_pubkey: Uint8Array; + sender_sig: Uint8Array; +} + +export interface RequestEnvelope { + update: UpdateEnvelope; + read_state: ReadStateEnvelope; +} + +/** + * The transaction data returned from the toJson() function of a transaction + */ +export interface TxData { + id?: string; + sender: string; + senderPublicKey: string; + recipient: string; + memo: number | BigInt; + feeAmount: string; + expirationTime: number | BigInt; + type?: BitGoTransactionType; +} + +export interface IcpTransactionExplanation extends BaseTransactionExplanation { + sender?: string; + type?: BitGoTransactionType; +} + +export interface NetworkIdentifier { + blockchain: string; + network: string; +} + +export interface SignedTransactionRequest { + network_identifier: NetworkIdentifier; + signed_transaction: string; +} diff --git a/modules/sdk-coin-icp/src/lib/index.ts b/modules/sdk-coin-icp/src/lib/index.ts index 838a26ae4eb..d7a5114ee19 100644 --- a/modules/sdk-coin-icp/src/lib/index.ts +++ b/modules/sdk-coin-icp/src/lib/index.ts @@ -1,5 +1,8 @@ import * as Utils from './utils'; +export { KeyPair } from './keyPair'; export { TransactionBuilder } from './transactionBuilder'; export { TransferBuilder } from './transferBuilder'; +export { TransactionBuilderFactory } from './transactionBuilderFactory'; +export { Transaction } from './transaction'; export { Utils }; diff --git a/modules/sdk-coin-icp/src/lib/protoDefinition.ts b/modules/sdk-coin-icp/src/lib/protoDefinition.ts new file mode 100644 index 00000000000..45cac659cdd --- /dev/null +++ b/modules/sdk-coin-icp/src/lib/protoDefinition.ts @@ -0,0 +1,40 @@ +export const protoDefinition = ` +syntax = "proto3"; + +message Memo { + uint64 memo = 1; +} + +message Tokens { + uint64 e8s = 1; +} + +message Payment { + Tokens receiver_gets = 1; +} + +message Subaccount { + bytes sub_account = 1; +} + +message AccountIdentifier { + bytes hash = 1; +} + +message BlockIndex { + uint64 height = 1; +} + +message TimeStamp { + uint64 timestamp_nanos = 1; +} + +message SendRequest { + Memo memo = 1; + Payment payment = 2; + Tokens max_fee = 3; + Subaccount from_subaccount = 4; + AccountIdentifier to = 5; + BlockIndex created_at = 6; + TimeStamp created_at_time = 7; +}`; diff --git a/modules/sdk-coin-icp/src/lib/signedTransactionBuilder.ts b/modules/sdk-coin-icp/src/lib/signedTransactionBuilder.ts new file mode 100644 index 00000000000..b9c85d211d9 --- /dev/null +++ b/modules/sdk-coin-icp/src/lib/signedTransactionBuilder.ts @@ -0,0 +1,84 @@ +import { + cborUnsignedTransaction, + RequestType, + Signatures, + UpdateEnvelope, + ReadStateEnvelope, + RequestEnvelope, +} from './iface'; +import utils from './utils'; +import assert from 'assert'; + +export class SignedTransactionBuilder { + protected _unsigned_transaction: string; + protected _signaturePayload: Signatures[]; + + constructor(unsigned_transaction: string, signatures: Signatures[]) { + this._unsigned_transaction = unsigned_transaction; + this._signaturePayload = signatures; + } + + getSignTransaction(): string { + const combineRequest = { + signatures: this._signaturePayload, + unsigned_transaction: this._unsigned_transaction, + }; + const signatureMap = new Map(); + for (const sig of combineRequest.signatures) { + signatureMap.set(sig.signing_payload.hex_bytes, sig); + } + const unsignedTransaction = utils.cborDecode( + utils.blobFromHex(combineRequest.unsigned_transaction) + ) as cborUnsignedTransaction; + assert(combineRequest.signatures.length === unsignedTransaction.ingress_expiries.length * 2); + assert(unsignedTransaction.updates.length === 1); + const envelopes = this.getEnvelopes(unsignedTransaction, signatureMap); + const envelopRequests = { requests: envelopes }; + const signedTransaction = utils.cborEncode(envelopRequests); + return signedTransaction; + } + + getEnvelopes( + unsignedTransaction: cborUnsignedTransaction, + signatureMap: Map + ): [string, RequestEnvelope[]][] { + const envelopes: [string, RequestEnvelope[]][] = []; + for (const [reqType, update] of unsignedTransaction.updates) { + const requestEnvelopes: RequestEnvelope[] = []; + for (const ingressExpiry of unsignedTransaction.ingress_expiries) { + update.ingress_expiry = ingressExpiry; + + const readState = utils.makeReadStateFromUpdate(update); + const transactionSignature = utils.getTransactionSignature(signatureMap, update); + if (!transactionSignature) { + throw new Error('Transaction signature is undefined'); + } + + const readStateSignature = utils.getReadStateSignature(signatureMap, readState); + if (!readStateSignature) { + throw new Error('read state signature is undefined'); + } + + const pk_der = utils.getPublicKeyInDERFormat(transactionSignature.public_key.hex_bytes); + const updateEnvelope: UpdateEnvelope = { + content: { request_type: RequestType.CALL, ...update }, + sender_pubkey: pk_der, + sender_sig: utils.blobFromHex(transactionSignature.hex_bytes), + }; + + const readStateEnvelope: ReadStateEnvelope = { + content: { request_type: RequestType.READ_STATE, ...readState }, + sender_pubkey: pk_der, + sender_sig: utils.blobFromHex(readStateSignature.hex_bytes), + }; + + requestEnvelopes.push({ + update: updateEnvelope, + read_state: readStateEnvelope, + }); + } + envelopes.push([reqType, requestEnvelopes]); + } + return envelopes; + } +} diff --git a/modules/sdk-coin-icp/src/lib/transaction.ts b/modules/sdk-coin-icp/src/lib/transaction.ts new file mode 100644 index 00000000000..5edfaef1548 --- /dev/null +++ b/modules/sdk-coin-icp/src/lib/transaction.ts @@ -0,0 +1,212 @@ +import { + BaseKey, + BaseTransaction, + TransactionRecipient, + TransactionType, + InvalidTransactionError, + TransactionType as BitGoTransactionType, +} from '@bitgo/sdk-core'; +import { BaseCoin as CoinConfig } from '@bitgo/statics'; +import { + IcpTransaction, + IcpTransactionData, + PayloadsData, + OperationType, + Signatures, + TxData, + IcpTransactionExplanation, + SignedTransactionRequest, + Network, +} from './iface'; +import { Utils } from './utils'; +import { KeyPair } from './keyPair'; + +export class Transaction extends BaseTransaction { + protected _icpTransactionData: IcpTransactionData; + protected _icpTransaction: IcpTransaction; + protected _payloadsData: PayloadsData; + protected _signedTransaction: string; + protected _signaturePayload: Signatures[]; + protected _utils: Utils; + + constructor(_coinConfig: Readonly, utils: Utils) { + super(_coinConfig); + this._utils = utils; + } + + get icpTransactionData(): IcpTransactionData { + return this._icpTransactionData; + } + + set icpTransactionData(icpTransactionData: IcpTransactionData) { + this._icpTransactionData = icpTransactionData; + } + + get icpTransaction(): IcpTransaction { + return this._icpTransaction; + } + + set icpTransaction(icpTransaction: IcpTransaction) { + this._icpTransaction = icpTransaction; + } + + get unsignedTransaction(): string { + return this._payloadsData.unsigned_transaction; + } + + get signaturePayload(): Signatures[] { + return this._signaturePayload; + } + + set signedTransaction(signature: string) { + this._signedTransaction = signature; + } + + get signedTransaction(): string { + return this._signedTransaction; + } + + set payloadsData(payloadsData: PayloadsData) { + this._payloadsData = payloadsData; + } + + get payloadsData(): PayloadsData { + return this._payloadsData; + } + + fromRawTransaction(rawTransaction: string): void { + try { + const parsedTx = JSON.parse(rawTransaction); + switch (parsedTx.type) { + case OperationType.TRANSACTION: + this._icpTransactionData = { + senderAddress: parsedTx.address, + receiverAddress: parsedTx.externalOutputs[0].address, + amount: parsedTx.spendAmountString, + fee: parsedTx.fee, + senderPublicKeyHex: parsedTx.senderKey, + memo: parsedTx.seqno, + transactionType: parsedTx.type, + expiryTime: parsedTx.expiryTime, + }; + this._utils.validateRawTransaction(this._icpTransactionData); + break; + default: + throw new Error('Invalid transaction type'); + } + } catch (error) { + throw new InvalidTransactionError('Invalid raw transaction'); + } + } + + addSignature(signaturePayloads: Signatures[]): void { + if (!signaturePayloads) { + throw new Error('signatures not provided'); + } + if (signaturePayloads.length !== this._payloadsData.payloads.length) { + throw new Error('signatures length is not matching'); + } + this._signaturePayload = signaturePayloads; + } + + /** @inheritdoc */ + toJson(): TxData { + if (!this._icpTransactionData) { + throw new InvalidTransactionError('Empty transaction'); + } + switch (this._icpTransactionData.transactionType) { + case OperationType.TRANSACTION: + return { + id: this._id, + sender: this._icpTransactionData.senderAddress, + senderPublicKey: this._icpTransactionData.senderPublicKeyHex, + recipient: this._icpTransactionData.receiverAddress, + memo: this._icpTransactionData.memo, + feeAmount: this._icpTransactionData.fee, + expirationTime: this._icpTransactionData.expiryTime, + type: BitGoTransactionType.Send, + }; + default: + throw new Error('Unsupported transaction type'); + } + } + + /** @inheritDoc */ + explainTransaction(): IcpTransactionExplanation { + const result = this.toJson(); + const displayOrder = ['id', 'outputAmount', 'changeAmount', 'outputs', 'changeOutputs', 'fee']; + const outputs: TransactionRecipient[] = []; + + const explanationResult = { + displayOrder, + id: this.id, + outputs, + outputAmount: '0', + fee: { fee: '0' }, + type: result.type, + changeOutputs: [], // account based does not use change outputs + changeAmount: '0', // account based does not make change + }; + + switch (explanationResult.type) { + case TransactionType.Send: + return this.explainTransferTransaction(explanationResult); + default: + throw new InvalidTransactionError('Transaction type not supported'); + } + } + + /** + * Explains a transfer transaction by providing details about the recipients and the total output amount. + * + * @param {IcpTransactionExplanation} explanationResult - The initial explanation result to be extended. + * @returns {IcpTransactionExplanation} The extended explanation result including the output amount and recipients. + */ + explainTransferTransaction(explanationResult: IcpTransactionExplanation): IcpTransactionExplanation { + explanationResult.fee = { fee: this.icpTransactionData.fee }; + const recipients = this._utils.getRecipients(this.icpTransactionData); + const outputs: TransactionRecipient[] = [recipients]; + const outputAmountBN = recipients.amount; + const outputAmount = outputAmountBN.toString(); + + return { + ...explanationResult, + outputAmount, + outputs, + }; + } + + /** @inheritdoc */ + toBroadcastFormat(): string { + if (!this._signedTransaction) { + throw new InvalidTransactionError('Empty transaction'); + } + return this.serialize(); + } + + serialize(): string { + const transaction: SignedTransactionRequest = { + signed_transaction: this._signedTransaction, + network_identifier: { + blockchain: this._coinConfig.fullName, + network: Network.ID, + }, + }; + return JSON.stringify(transaction); + } + + /** @inheritdoc */ + canSign(key: BaseKey): boolean { + try { + const keyPair = new KeyPair({ prv: key.key }); + const publicKeyHex = keyPair.getPublicKey({ compressed: true }).toString('hex'); + const uncompressedPublicKeyHex = keyPair.getPublicKey({ compressed: false }).toString('hex'); + return ( + this.icpTransactionData.senderPublicKeyHex === publicKeyHex || + this.icpTransactionData.senderPublicKeyHex === uncompressedPublicKeyHex + ); + } catch (error) { + return false; + } + } +} diff --git a/modules/sdk-coin-icp/src/lib/transactionBuilder.ts b/modules/sdk-coin-icp/src/lib/transactionBuilder.ts index 3a167ca39d9..329649d16a6 100644 --- a/modules/sdk-coin-icp/src/lib/transactionBuilder.ts +++ b/modules/sdk-coin-icp/src/lib/transactionBuilder.ts @@ -1,97 +1,147 @@ import { BaseCoin as CoinConfig } from '@bitgo/statics'; -import { - BaseKey, - BaseTransaction, - PublicKey as BasePublicKey, - BaseTransactionBuilder, - BaseAddress, - Recipient, -} from '@bitgo/sdk-core'; -import { TransferBuilder } from './transferBuilder'; +import BigNumber from 'bignumber.js'; +import { BaseKey, BaseTransactionBuilder, BuildTransactionError, SigningError, BaseAddress } from '@bitgo/sdk-core'; +import { Transaction } from './transaction'; +import utils from './utils'; +import { IcpTransactionData } from './iface'; export abstract class TransactionBuilder extends BaseTransactionBuilder { - protected _transfer: TransferBuilder; + protected _transaction: Transaction; + protected _sender: string; + protected _publicKey: string; + protected _memo: number | BigInt; + protected _receiverId: string; + protected _amount: string; - protected constructor(_coinConfig: Readonly) { + constructor(_coinConfig: Readonly) { super(_coinConfig); - } - - /** @inheritdoc */ - protected signImplementation(key: BaseKey): BaseTransaction { - throw new Error('method not implemented'); + this._transaction = new Transaction(_coinConfig, utils); } /** - * add a signature to the transaction + * Sets the public key and the address of the sender of this transaction. + * + * @param {string} address the account that is sending this transaction + * @param {string} pubKey the public key that is sending this transaction + * @returns {TransactionBuilder} This transaction builder */ - addSignature(publicKey: BasePublicKey, signature: Buffer): void { - throw new Error('method not implemented'); + public sender(address: string, pubKey: string): this { + if (!address || !utils.isValidAddress(address.toString())) { + throw new BuildTransactionError('Invalid or missing address, got: ' + address); + } + if (!pubKey || !utils.isValidPublicKey(pubKey)) { + throw new BuildTransactionError('Invalid or missing pubKey, got: ' + pubKey); + } + this._sender = address; + this._publicKey = pubKey; + return this; } /** - * Sets the sender of this transaction. + * Set the memo + * + * @param {number} memo - number that to be used as memo + * @returns {TransactionBuilder} This transaction builder */ - sender(senderAddress: string): this { - throw new Error('method not implemented'); + public memo(memo: number): this { + if (memo < 0) { + throw new BuildTransactionError(`Invalid memo: ${memo}`); + } + this._memo = memo; + return this; } /** - * gets the gas data of this transaction. + * Sets the account Id of the receiver of this transaction. + * + * @param {string} accountId the account id of the account that is receiving this transaction + * @returns {TransactionBuilder} This transaction builder */ - gasData(): this { - throw new Error('method not implemented'); + public receiverId(accountId: string): this { + if (!accountId || !utils.isValidAddress(accountId)) { + throw new BuildTransactionError('Invalid or missing accountId for receiver, got: ' + accountId); + } + this._receiverId = accountId; + return this; } /** @inheritdoc */ - validateAddress(address: BaseAddress, addressFormat?: string): void { - throw new Error('method not implemented'); + get transaction(): Transaction { + return this._transaction; } - /** - * validates the recipients of the transaction - */ - validateRecipients(recipients: Recipient[]): void { - throw new Error('method not implemented'); + /** @inheritdoc */ + set transaction(transaction: Transaction) { + this._transaction = transaction; } - /** - * validates the gas data of the transaction - */ - validateGasData(): void { - throw new Error('method not implemented'); + get transactionType(): string { + return this._transaction.icpTransactionData.transactionType; } - /** - * validates the gas price of the transaction - */ - validateGasPrice(gasPrice: number): void { - throw new Error('method not implemented'); + /** @inheritdoc */ + fromImplementation(rawTransaction: IcpTransactionData): Transaction { + this.validateRawTransaction(rawTransaction); + this.buildImplementation(); + return this.transaction; } /** @inheritdoc */ - validateKey(key: BaseKey): void { - throw new Error('method not implemented'); + validateTransaction(transaction: Transaction): void { + if (!transaction || !transaction.icpTransactionData) { + return; + } + utils.validateRawTransaction(transaction.icpTransactionData); } - /** @inheritdoc */ - validateRawTransaction(rawTransaction: string): void { - throw new Error('method not implemented'); + /** + * Sets the amount of this transaction. + * + * @param {string} value the amount to be sent in e8s (1 ICP = 1e8 e8s) + * @returns {TransactionBuilder} This transaction builder + */ + public amount(value: string): this { + utils.validateValue(new BigNumber(value)); + this._amount = value; + return this; } - /** @inheritdoc */ - validateValue(): void { - throw new Error('method not implemented'); + validateValue(value: BigNumber): void { + utils.validateValue(new BigNumber(value)); } /** - * Validates the specific transaction builder internally + * Initialize the transaction builder fields using the decoded transaction data + * + * @param {Transaction} tx the transaction data */ - validateDecodedTransaction(): void { - throw new Error('method not implemented'); + initBuilder(tx: Transaction): void { + this._transaction = tx; + const icpTransactionData = tx.icpTransactionData; + this._sender = icpTransactionData.senderAddress; + this._memo = icpTransactionData.memo; + this._receiverId = icpTransactionData.receiverAddress; + this._publicKey = icpTransactionData.senderPublicKeyHex; + this._amount = icpTransactionData.amount; } /** @inheritdoc */ - validateTransaction(): void { - throw new Error('method not implemented'); + validateKey(key: BaseKey): void { + if (!key || !key.key) { + throw new SigningError('Key is required'); + } + if (!utils.isValidPrivateKey(key.key)) { + throw new SigningError('Invalid private key'); + } + } + + validateAddress(address: BaseAddress): void { + if (!utils.isValidAddress(address.address)) { + throw new BuildTransactionError('Invalid address'); + } + } + + validateRawTransaction(rawTransaction: IcpTransactionData): void { + utils.validateRawTransaction(rawTransaction); } } diff --git a/modules/sdk-coin-icp/src/lib/transactionBuilderFactory.ts b/modules/sdk-coin-icp/src/lib/transactionBuilderFactory.ts index c971054b91b..e6fe235605b 100644 --- a/modules/sdk-coin-icp/src/lib/transactionBuilderFactory.ts +++ b/modules/sdk-coin-icp/src/lib/transactionBuilderFactory.ts @@ -1,5 +1,10 @@ -import { BaseTransactionBuilderFactory } from '@bitgo/sdk-core'; +import { BaseTransactionBuilderFactory, InvalidTransactionError } from '@bitgo/sdk-core'; import { BaseCoin as CoinConfig } from '@bitgo/statics'; +import { Transaction } from './transaction'; +import { TransactionBuilder } from './transactionBuilder'; +import { TransferBuilder } from './transferBuilder'; +import { Utils } from './utils'; +import { OperationType } from './iface'; export class TransactionBuilderFactory extends BaseTransactionBuilderFactory { constructor(_coinConfig: Readonly) { @@ -7,32 +12,45 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory { } /** @inheritdoc */ - from(): void { - throw new Error('method not implemented'); + from(rawTransaction: string): TransactionBuilder { + const transaction = new Transaction(this._coinConfig, new Utils()); + transaction.fromRawTransaction(rawTransaction); + try { + switch (transaction.icpTransactionData.transactionType) { + case OperationType.TRANSACTION: + return this.getTransferBuilder(transaction); + default: + throw new InvalidTransactionError('Invalid transaction'); + } + } catch (e) { + throw new InvalidTransactionError('Invalid transaction: ' + e.message); + } } - /** @inheritdoc */ - getTransferBuilder(): void { - throw new Error('method not implemented'); - } - - /** @inheritdoc */ - getStakingBuilder(): void { - throw new Error('method not implemented'); - } - - /** @inheritdoc */ - getUnstakingBuilder(): void { - throw new Error('method not implemented'); + /** + * Initialize the builder with the given transaction + * + * @param {Transaction | undefined} tx - the transaction used to initialize the builder + * @param {TransactionBuilder} builder - the builder to be initialized + * @returns {TransactionBuilder} the builder initialized + */ + private static initializeBuilder(tx: Transaction | undefined, builder: T): T { + if (tx) { + builder.initBuilder(tx); + } + return builder; } /** @inheritdoc */ - getCustomTransactionBuilder(): void { - throw new Error('method not implemented'); + getTransferBuilder(tx?: Transaction): TransferBuilder { + return TransactionBuilderFactory.initializeBuilder(tx, new TransferBuilder(this._coinConfig, new Utils())); } - /** @inheritdoc */ - getTokenTransferBuilder(): void { + //TODO WIN-4723 need to implement the following method + /** + * Parse the transaction from a raw transaction + */ + private parseTransaction(rawTransaction: string): void { throw new Error('method not implemented'); } @@ -40,11 +58,4 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory { getWalletInitializationBuilder(): void { throw new Error('method not implemented'); } - - /** - * Parse the transaction from a raw transaction - */ - private parseTransaction(rawTransaction: string): void { - throw new Error('method not implemented'); - } } diff --git a/modules/sdk-coin-icp/src/lib/transferBuilder.ts b/modules/sdk-coin-icp/src/lib/transferBuilder.ts index 87dc3c05ccb..ed2d3843020 100644 --- a/modules/sdk-coin-icp/src/lib/transferBuilder.ts +++ b/modules/sdk-coin-icp/src/lib/transferBuilder.ts @@ -1,74 +1,134 @@ import { BaseCoin as CoinConfig } from '@bitgo/statics'; import { TransactionBuilder } from './transactionBuilder'; -import { BaseKey, Recipient, TransactionType, BaseTransaction } from '@bitgo/sdk-core'; +import { BaseTransaction, BaseKey, SigningError, BuildTransactionError } from '@bitgo/sdk-core'; +import { Utils } from './utils'; +import { Transaction } from './transaction'; +import { UnsignedTransactionBuilder } from './unsignedTransactionBuilder'; +import { + CurveType, + IcpMetadata, + IcpOperation, + IcpPublicKey, + IcpTransaction, + IcpTransactionData, + OperationType, +} from './iface'; +import { SignedTransactionBuilder } from './signedTransactionBuilder'; +import { KeyPair } from './keyPair'; +import assert from 'assert'; export class TransferBuilder extends TransactionBuilder { - protected _recipients: Recipient[]; + protected _utils: Utils; - constructor(_coinConfig: Readonly) { + constructor(_coinConfig: Readonly, utils: Utils) { super(_coinConfig); + this._utils = utils; } - protected get transactionType(): TransactionType { - return TransactionType.Send; - } - - send(recipients: Recipient[]): this { - this.validateRecipients(recipients); - this._recipients = recipients; - return this; + /** + * Initialize the transaction builder fields using the decoded transaction data + * + * @param {Transaction} tx the transaction data + */ + initBuilder(tx: Transaction): void { + super.initBuilder(tx); } /** @inheritdoc */ - validateTransaction(): void { - throw new Error('method not implemented'); + protected async buildImplementation(): Promise { + this.validateTransaction(this._transaction); + this.buildIcpTransactionData(); + const unsignedTransactionBuilder = new UnsignedTransactionBuilder(this._transaction.icpTransaction); + const payloadsData = await unsignedTransactionBuilder.getUnsignedTransaction(); + this._transaction.payloadsData = payloadsData; + return this._transaction; } - /** @inheritdoc */ - sign(key: BaseKey): void { - throw new Error('method not implemented'); - } + protected buildIcpTransactionData(): void { + assert(this._sender, new BuildTransactionError('sender is required before building')); + assert(this._publicKey, new BuildTransactionError('sender public key is required before building')); + assert(this._amount, new BuildTransactionError('amount is required before building')); + assert(this._receiverId, new BuildTransactionError('receiver is required before building')); + assert(this._memo, new BuildTransactionError('memo is required before building')); + const publicKey: IcpPublicKey = { + hex_bytes: this._publicKey, + curve_type: CurveType.SECP256K1, + }; - /** @inheritdoc */ - protected async buildImplementation(): Promise { - throw new Error('method not implemented'); - } + const senderOperation: IcpOperation = { + type: OperationType.TRANSACTION, + account: { address: this._sender }, + amount: { + value: `-${this._amount}`, + currency: { + symbol: this._coinConfig.family, + decimals: this._coinConfig.decimalPlaces, + }, + }, + }; - /** - * Initialize the transaction builder fields using the decoded transaction data - */ - initBuilder(): void { - throw new Error('method not implemented'); - } - - /** - * Validates all fields are defined - */ - private validateTransactionFields(): void { - throw new Error('method not implemented'); - } + const receiverOperation: IcpOperation = { + type: OperationType.TRANSACTION, + account: { address: this._receiverId }, + amount: { + value: this._amount, + currency: { + symbol: this._coinConfig.family, + decimals: this._coinConfig.decimalPlaces, + }, + }, + }; - /** - * Build transfer programmable transaction - * - * @protected - */ - protected buildIcpTransaction(): void { - throw new Error('method not implemented'); - } + const feeOperation: IcpOperation = { + type: OperationType.FEE, + account: { address: this._sender }, + amount: { + value: this._utils.gasData(), + currency: { + symbol: this._coinConfig.family, + decimals: this._coinConfig.decimalPlaces, + }, + }, + }; - /** @inheritdoc */ - TransactionBuilder(): void { - throw new Error('method not implemented'); - } + const { metaData, ingressEndTime }: { metaData: IcpMetadata; ingressEndTime: number | BigInt } = + this._utils.getMetaData(this._memo); - /** @inheritdoc */ - fromImplementation(): BaseTransaction { - throw new Error('method not implemented'); + const icpTransaction: IcpTransaction = { + public_keys: [publicKey], + operations: [senderOperation, receiverOperation, feeOperation], + metadata: metaData, + }; + const icpTransactionData: IcpTransactionData = { + senderAddress: this._sender, + receiverAddress: this._receiverId, + amount: this._amount, + fee: this._utils.gasData(), + senderPublicKeyHex: this._publicKey, + memo: this._memo, + transactionType: OperationType.TRANSACTION, + expiryTime: ingressEndTime, + }; + this._transaction.icpTransactionData = icpTransactionData; + this._transaction.icpTransaction = icpTransaction; } /** @inheritdoc */ - get transaction(): BaseTransaction { - throw new Error('method not implemented'); + protected signImplementation(key: BaseKey): BaseTransaction { + this.validateKey(key); + if (!this.transaction.canSign(key)) { + throw new SigningError('Private key cannot sign the transaction'); + } + const keyPair = new KeyPair({ prv: key.key }); + const keys = keyPair.getKeys(); + if (!keys.prv) { + throw new SigningError('invalid private key'); + } + const signedTransactionBuilder = new SignedTransactionBuilder( + this._transaction.unsignedTransaction, + this._transaction.signaturePayload + ); + this._transaction.signedTransaction = signedTransactionBuilder.getSignTransaction(); + return this._transaction; } } diff --git a/modules/sdk-coin-icp/src/lib/unsignedTransactionBuilder.ts b/modules/sdk-coin-icp/src/lib/unsignedTransactionBuilder.ts new file mode 100644 index 00000000000..eabc00d4bf3 --- /dev/null +++ b/modules/sdk-coin-icp/src/lib/unsignedTransactionBuilder.ts @@ -0,0 +1,134 @@ +import { + IcpTransaction, + SendArgs, + HttpCanisterUpdate, + SigningPayload, + PayloadsData, + SignatureType, + OperationType, + MethodName, +} from './iface'; +import protobuf from 'protobufjs'; +import utils from './utils'; +import { protoDefinition } from './protoDefinition'; + +const MAX_INGRESS_TTL = 5 * 60 * 1000_000_000; // 5 minutes in nanoseconds +const PERMITTED_DRIFT = 60 * 1000_000_000; // 60 seconds in nanoseconds +const LEDGER_CANISTER_ID = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 2, 1, 1]); // Uint8Array value for "00000000000000020101" and the string value is "ryjl3-tyaaa-aaaaa-aaaba-cai" + +export class UnsignedTransactionBuilder { + private _icpTransactionPayload: IcpTransaction; + constructor(icpTransactionPayload: IcpTransaction) { + this._icpTransactionPayload = icpTransactionPayload; + } + + async getUnsignedTransaction(): Promise { + const interval = MAX_INGRESS_TTL - PERMITTED_DRIFT - 120 * 1000_000_000; // 120 seconds in milliseconds + const ingressExpiries = this.getIngressExpiries( + this._icpTransactionPayload.metadata.ingress_start, + this._icpTransactionPayload.metadata.ingress_end, + interval + ); + const sendArgs = this.getSendArgs( + this._icpTransactionPayload.metadata.memo, + this._icpTransactionPayload.metadata.created_at_time, + this._icpTransactionPayload.operations[1].amount.value, + this._icpTransactionPayload.operations[2].amount.value, + this._icpTransactionPayload.operations[1].account.address + ); + const update = await this.getUpdate(sendArgs, this._icpTransactionPayload.public_keys[0].hex_bytes); + const updates: [string, HttpCanisterUpdate][] = []; + updates.push([OperationType.TRANSACTION, update]); + const txn = { updates: updates, ingress_expiries: ingressExpiries }; + const unsignedTransaction = utils.cborEncode(txn); + const payloads: SigningPayload[] = []; + this.getPayloads(payloads, ingressExpiries, this._icpTransactionPayload.operations[0].account.address, update); + const payloadsData = { + payloads: payloads, + unsigned_transaction: unsignedTransaction, + }; + return payloadsData; + } + + getPayloads( + payloads: SigningPayload[], + ingressExpiries: bigint[], + accountAddress: string, + update: HttpCanisterUpdate + ): SigningPayload[] { + for (const ingressExpiry of ingressExpiries) { + const clonedUpdate: HttpCanisterUpdate = { + canister_id: Buffer.from(update.canister_id), + method_name: update.method_name, + arg: update.arg, + sender: update.sender, + ingress_expiry: ingressExpiry, + }; + + const representationIndependentHash = utils.HttpCanisterUpdateRepresentationIndependentHash(clonedUpdate); + const transactionPayload: SigningPayload = { + hex_bytes: utils.blobToHex(utils.makeSignatureData(representationIndependentHash)), + account_identifier: { address: accountAddress }, + signature_type: SignatureType.ECDSA, + }; + payloads.push(transactionPayload); + + const readState = utils.makeReadStateFromUpdate(clonedUpdate); + const readStateMessageId = utils.HttpReadStateRepresentationIndependentHash(readState); + const readStatePayload: SigningPayload = { + hex_bytes: utils.blobToHex(utils.makeSignatureData(readStateMessageId)), + account_identifier: { address: accountAddress }, + signature_type: SignatureType.ECDSA, + }; + payloads.push(readStatePayload); + } + + return payloads; + } + + getIngressExpiries(ingressStartTime: number | BigInt, ingressEndTime: number | BigInt, interval: number): bigint[] { + const ingressExpiries: bigint[] = []; + + for (let now = Number(ingressStartTime); now < Number(ingressEndTime); now += interval) { + const ingressExpiry = BigInt(now + (MAX_INGRESS_TTL - PERMITTED_DRIFT)); + ingressExpiries.push(ingressExpiry); + } + + return ingressExpiries; + } + + getSendArgs(memo: number | BigInt, created_at_time: number, amount: string, fee: string, receiver: string): SendArgs { + const sendArgs: SendArgs = { + memo: { memo: memo }, + payment: { receiverGets: { e8s: Number(amount) } }, + maxFee: { e8s: -Number(fee) }, + to: { hash: Buffer.from(receiver, 'hex') }, + createdAtTime: { timestampNanos: Number(created_at_time) }, + }; + return sendArgs; + } + + async toArg(args: SendArgs): Promise { + const root = await protobuf.parse(protoDefinition).root; + const SendRequestMessage = root.lookupType('SendRequest'); + const errMsg = SendRequestMessage.verify(args); + if (errMsg) throw new Error(errMsg); + const message = SendRequestMessage.create(args); + return SendRequestMessage.encode(message).finish(); + } + + async getUpdate(sendArgs: SendArgs, publicKeyHex: string): Promise { + const principalId = utils.getPrincipalIdFromPublicKey(publicKeyHex).toUint8Array(); + const senderBlob = Buffer.from(principalId); + const canisterIdBuffer = Buffer.from(LEDGER_CANISTER_ID); + const args = await this.toArg(sendArgs); + const update: HttpCanisterUpdate = { + canister_id: canisterIdBuffer, + method_name: MethodName.SEND_PB, + arg: args, + sender: senderBlob, + ingress_expiry: 0n, + }; + return update; + } +} diff --git a/modules/sdk-coin-icp/src/lib/utils.ts b/modules/sdk-coin-icp/src/lib/utils.ts index 1c94b77096d..90cc0cc6a01 100644 --- a/modules/sdk-coin-icp/src/lib/utils.ts +++ b/modules/sdk-coin-icp/src/lib/utils.ts @@ -1,47 +1,123 @@ -import { BaseUtils, KeyPair } from '@bitgo/sdk-core'; -import { secp256k1 } from '@noble/curves/secp256k1'; +import { BaseUtils, KeyPair, ParseTransactionError, Recipient, BuildTransactionError } from '@bitgo/sdk-core'; import { Principal as DfinityPrincipal } from '@dfinity/principal'; import * as agent from '@dfinity/agent'; import crypto from 'crypto'; import crc32 from 'crc-32'; +import { HttpCanisterUpdate, IcpTransactionData, ReadState, RequestType, Signatures, IcpMetadata } from './iface'; import { KeyPair as IcpKeyPair } from './keyPair'; +import { decode, encode } from 'cbor-x'; // The "cbor-x" library is used here because it supports modern features like BigInt. do not replace it with "cbor as "cbor" is not compatible with Rust's serde_cbor when handling big numbers. +import js_sha256 from 'js-sha256'; +import BigNumber from 'bignumber.js'; +import { secp256k1 } from '@noble/curves/secp256k1'; + +export const REQUEST_STATUS = 'request_status'; export class Utils implements BaseUtils { - isValidAddress(address: string): boolean { + /** @inheritdoc */ + isValidTransactionId(txId: string): boolean { throw new Error('Method not implemented.'); } - isValidTransactionId(txId: string): boolean { + /** @inheritdoc */ + isValidBlockId(hash: string): boolean { throw new Error('Method not implemented.'); } - isValidPublicKey(hexStr: string): boolean { - if (!this.isValidHex(hexStr)) { - return false; - } + /** @inheritdoc */ + isValidSignature(signature: string): boolean { + throw new Error('Method not implemented.'); + } + + /** + * gets the gas data of this transaction. + */ + //TODO WIN-4242: to moved to a config and eventually to an API for dynamic value + gasData(): string { + return '-10000'; + } + + /** + * Checks if the provided address is a valid hexadecimal string. + * + * @param {string} address - The address to validate. + * @returns {boolean} - Returns `true` if the address is a valid 64-character hexadecimal string, otherwise `false`. + */ + isValidAddress(address: string): boolean { + return typeof address === 'string' && /^[0-9a-fA-F]{64}$/.test(address); + } - if (!this.isValidLength(hexStr)) { + /** + * Checks if the provided hex string is a valid public key. + * + * A valid public key can be either compressed or uncompressed: + * - Compressed public keys are 33 bytes long and start with either 0x02 or 0x03. + * - Uncompressed public keys are 65 bytes long and start with 0x04. + * + * @param {string} hexStr - The hex string representation of the public key to validate. + * @returns {boolean} - Returns `true` if the hex string is a valid public key, otherwise `false`. + */ + isValidPublicKey(hexStr: string): boolean { + if (!this.isValidHex(hexStr) || !this.isValidLength(hexStr)) { return false; } const pubKeyBytes = this.hexToBytes(hexStr); const firstByte = pubKeyBytes[0]; - return ( - (pubKeyBytes.length === 33 && (firstByte === 2 || firstByte === 3)) || - (pubKeyBytes.length === 65 && firstByte === 4) - ); + const validCompressed = pubKeyBytes.length === 33 && (firstByte === 2 || firstByte === 3); + const validUncompressed = pubKeyBytes.length === 65 && firstByte === 4; + + return validCompressed || validUncompressed; + } + + /** + * Encodes a value into CBOR format and returns it as a hex string. + * + * @param {unknown} value - The value to encode. + * @returns {string} - The CBOR encoded value as a hex string. + */ + cborEncode(value: unknown): string { + if (value === undefined) { + throw new Error('Value to encode cannot be undefined.'); + } + const cborData = encode(value); + return Buffer.from(cborData).toString('hex'); } + /** + * Checks if the length of the given hexadecimal string is valid. + * A valid length is either 66 characters (33 bytes) or 130 characters (65 bytes). + * + * @param {string} hexStr - The hexadecimal string to check. + * @returns {boolean} - Returns `true` if the length is valid, otherwise `false`. + */ isValidLength(hexStr: string): boolean { return hexStr.length / 2 === 33 || hexStr.length / 2 === 65; } + /** + * Checks if the provided string is a valid hexadecimal string. + * + * A valid hexadecimal string consists of pairs of hexadecimal digits (0-9, a-f, A-F). + * + * @param hexStr - The string to be validated as a hexadecimal string. + * @returns True if the string is a valid hexadecimal string, false otherwise. + */ isValidHex(hexStr: string): boolean { return /^([0-9a-fA-F]{2})+$/.test(hexStr); } + /** + * Converts a hexadecimal string to a Uint8Array. + * + * @param {string} hex - The hexadecimal string to convert. + * @returns {Uint8Array} The resulting byte array. + */ hexToBytes(hex: string): Uint8Array { - return new Uint8Array(Buffer.from(hex, 'hex')); + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + bytes[i / 2] = parseInt(hex.substr(i, 2), 16); + } + return bytes; } /** @inheritdoc */ @@ -49,6 +125,16 @@ export class Utils implements BaseUtils { return this.isValidKey(key); } + /** + * Validates whether the provided key is a valid ICP private key. + * + * This function attempts to create a new instance of `IcpKeyPair` using the provided key. + * If the key is valid, the function returns `true`. If the key is invalid, an error is thrown, + * and the function returns `false`. + * + * @param {string} key - The private key to validate. + * @returns {boolean} - `true` if the key is valid, `false` otherwise. + */ isValidKey(key: string): boolean { try { new IcpKeyPair({ prv: key }); @@ -58,27 +144,13 @@ export class Utils implements BaseUtils { } } - isValidSignature(signature: string): boolean { - throw new Error('Method not implemented.'); - } - - isValidBlockId(hash: string): boolean { - throw new Error('Method not implemented.'); - } - - getHeaders(): Record { - return { - 'Content-Type': 'application/json', - }; - } - - getNetworkIdentifier(): Record { - return { - blockchain: 'Internet Computer', - network: '00000000000000020101', - }; - } - + /** + * Compresses an uncompressed public key. + * + * @param {string} uncompressedKey - The uncompressed public key in hexadecimal format. + * @returns {string} - The compressed public key in hexadecimal format. + * @throws {Error} - If the input key is not a valid uncompressed public key. + */ compressPublicKey(uncompressedKey: string): string { if (uncompressedKey.startsWith('02') || uncompressedKey.startsWith('03')) { return uncompressedKey; @@ -92,34 +164,64 @@ export class Utils implements BaseUtils { const y = BigInt(`0x${yHex}`); const prefix = y % 2n === 0n ? '02' : '03'; - return prefix + xHex; + return `${prefix}${xHex}`; } - getCurveType(): string { - return 'secp256k1'; + /** + * Converts a public key from its hexadecimal string representation to DER format. + * + * @param {string} publicKeyHex - The public key in hexadecimal string format. + * @returns The public key in DER format as a Uint8Array. + */ + getPublicKeyInDERFormat(publicKeyHex: string): Uint8Array { + const publicKeyBuffer = Buffer.from(publicKeyHex, 'hex'); + const ellipticKey = secp256k1.ProjectivePoint.fromHex(publicKeyBuffer.toString('hex')); + const uncompressedPublicKeyHex = ellipticKey.toHex(false); + const derEncodedKey = agent.wrapDER(Buffer.from(uncompressedPublicKeyHex, 'hex'), agent.SECP256K1_OID); + return derEncodedKey; } + /** + * Converts a public key in hexadecimal format to a Dfinity Principal ID. + * + * @param {string} publicKeyHex - The public key in hexadecimal format. + * @returns The corresponding Dfinity Principal ID. + */ + getPrincipalIdFromPublicKey(publicKeyHex: string): DfinityPrincipal { + const derEncodedKey = this.getPublicKeyInDERFormat(publicKeyHex); + const principalId = DfinityPrincipal.selfAuthenticating(Buffer.from(derEncodedKey)); + return principalId; + } + + /** + * Derives a DfinityPrincipal from a given public key in hexadecimal format. + * + * @param {string} publicKeyHex - The public key in hexadecimal format. + * @returns The derived DfinityPrincipal. + * @throws Will throw an error if the principal cannot be derived from the public key. + */ derivePrincipalFromPublicKey(publicKeyHex: string): DfinityPrincipal { try { - const point = secp256k1.ProjectivePoint.fromHex(publicKeyHex); - const uncompressedPublicKeyHex = point.toHex(false); - const derEncodedKey = agent.wrapDER(Buffer.from(uncompressedPublicKeyHex, 'hex'), agent.SECP256K1_OID); + const derEncodedKey = this.getPublicKeyInDERFormat(publicKeyHex); const principalId = DfinityPrincipal.selfAuthenticating(Buffer.from(derEncodedKey)); const principal = DfinityPrincipal.fromUint8Array(principalId.toUint8Array()); return principal; } catch (error) { - throw new Error(`Failed to process the public key: ${error.message}`); + throw new Error(`Failed to derive principal from public key: ${error.message}`); } } + /** + * Converts a DfinityPrincipal and an optional subAccount to a string representation of an account ID. + * + * @param {DfinityPrincipal} principal - The principal to convert. + * @param {Uint8Array} [subAccount=new Uint8Array(32)] - An optional sub-account, defaults to a 32-byte array of zeros. + * @returns {string} The hexadecimal string representation of the account ID. + */ fromPrincipal(principal: DfinityPrincipal, subAccount: Uint8Array = new Uint8Array(32)): string { - const ACCOUNT_ID_PREFIX = new Uint8Array([0x0a, ...Buffer.from('account-id')]); - const principalBytes = principal.toUint8Array(); - const combinedBytes = new Uint8Array(ACCOUNT_ID_PREFIX.length + principalBytes.length + subAccount.length); - - combinedBytes.set(ACCOUNT_ID_PREFIX, 0); - combinedBytes.set(principalBytes, ACCOUNT_ID_PREFIX.length); - combinedBytes.set(subAccount, ACCOUNT_ID_PREFIX.length + principalBytes.length); + const ACCOUNT_ID_PREFIX = Buffer.from([0x0a, ...Buffer.from('account-id')]); + const principalBytes = Buffer.from(principal.toUint8Array()); + const combinedBytes = Buffer.concat([ACCOUNT_ID_PREFIX, principalBytes, subAccount]); const sha224Hash = crypto.createHash('sha224').update(combinedBytes).digest(); const checksum = Buffer.alloc(4); @@ -129,26 +231,346 @@ export class Utils implements BaseUtils { return accountIdBytes.toString('hex'); } + /** + * Retrieves the address associated with a given hex-encoded public key. + * + * @param {string} hexEncodedPublicKey - The public key in hex-encoded format. + * @returns {Promise} A promise that resolves to the address derived from the provided public key. + * @throws {Error} Throws an error if the provided public key is not in a valid hex-encoded format. + */ async getAddressFromPublicKey(hexEncodedPublicKey: string): Promise { - const isKeyValid = this.isValidPublicKey(hexEncodedPublicKey); - if (!isKeyValid) { - throw new Error('Public Key is not in a valid Hex Encoded Format'); + if (!this.isValidPublicKey(hexEncodedPublicKey)) { + throw new Error('Invalid hex-encoded public key format.'); } const compressedKey = this.compressPublicKey(hexEncodedPublicKey); - const KeyPair = new IcpKeyPair({ pub: compressedKey }); - return KeyPair.getAddress(); + const keyPair = new IcpKeyPair({ pub: compressedKey }); + return keyPair.getAddress(); } + /** + * Generates a new key pair. If a seed is provided, it will be used to generate the key pair. + * + * @param {Buffer} [seed] - Optional seed for key generation. + * @returns {KeyPair} - The generated key pair containing both public and private keys. + * @throws {Error} - If the private key is missing in the generated key pair. + */ public generateKeyPair(seed?: Buffer): KeyPair { const keyPair = seed ? new IcpKeyPair({ seed }) : new IcpKeyPair(); - const keys = keyPair.getKeys(); - if (!keys.prv) { - throw new Error('Missing prv in key generation.'); + const { pub, prv } = keyPair.getKeys(); + if (!prv) { + throw new Error('Private key is missing in the generated key pair.'); + } + return { pub, prv }; + } + + validateFee(fee: string): void { + if (new BigNumber(fee).isEqualTo(0)) { + throw new BuildTransactionError('Fee equal to zero'); + } + if (fee !== this.gasData()) { + throw new BuildTransactionError('Invalid fee value'); + } + } + + /** @inheritdoc */ + validateValue(value: BigNumber): void { + if (value.isLessThanOrEqualTo(0)) { + throw new BuildTransactionError('amount cannot be less than or equal to zero'); } + } + + validateMemo(memo: number | BigInt): void { + if (Number(memo) < 0 || Number(memo) === null || Number(memo) === undefined || Number.isNaN(Number(memo))) { + throw new BuildTransactionError('Invalid memo'); + } + } + + validateExpireTime(expireTime: number | BigInt): void { + if (Number(expireTime) < Date.now() * 1000_000) { + throw new BuildTransactionError('Invalid expiry time'); + } + } + + /** + * Validates the raw transaction data to ensure it has a valid format in the blockchain context. + * + * @param {IcpTransactionData} transactionData - The transaction data to validate. + * @throws {ParseTransactionError} If the transaction data is invalid. + */ + validateRawTransaction(transactionData: IcpTransactionData): void { + if (!transactionData) { + throw new ParseTransactionError('Transaction data is missing.'); + } + const { senderPublicKeyHex, senderAddress, receiverAddress } = transactionData; + if (!this.isValidPublicKey(senderPublicKeyHex)) { + throw new ParseTransactionError('Sender public key is invalid.'); + } + if (!this.isValidAddress(senderAddress)) { + throw new ParseTransactionError('Sender address is invalid.'); + } + if (!this.isValidAddress(receiverAddress)) { + throw new ParseTransactionError('Receiver address is invalid.'); + } + this.validateFee(transactionData.fee); + this.validateValue(new BigNumber(transactionData.amount)); + this.validateMemo(transactionData.memo); + this.validateExpireTime(transactionData.expiryTime); + } + + /** + * + * @param {object} update + * @returns {Buffer} + */ + generateHttpCanisterUpdateId(update: HttpCanisterUpdate): Buffer { + return this.HttpCanisterUpdateRepresentationIndependentHash(update); + } + + /** + * Generates a representation-independent hash for an HTTP canister update. + * + * @param {HttpCanisterUpdate} update - The HTTP canister update object. + * @returns {Buffer} - The hash of the update object. + */ + HttpCanisterUpdateRepresentationIndependentHash(update: HttpCanisterUpdate): Buffer { + const updateMap = { + request_type: RequestType.CALL, + canister_id: update.canister_id, + method_name: update.method_name, + arg: update.arg, + ingress_expiry: update.ingress_expiry, + sender: update.sender, + }; + return this.hashOfMap(updateMap); + } + + /** + * Generates a SHA-256 hash for a given map object. + * + * @param {Record} map - The map object to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + */ + hashOfMap(map: Record): Buffer { + const hashes: Buffer[] = []; + for (const key in map) { + hashes.push(this.hashKeyVal(key, map[key])); + } + hashes.sort((buf0, buf1) => buf0.compare(buf1)); + return this.sha256(hashes); + } + + /** + * Generates a hash for a key-value pair. + * + * @param {string} key - The key to hash. + * @param {string | Buffer | BigInt} val - The value to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + */ + hashKeyVal(key: string, val: any): Buffer { + const keyHash = this.hashString(key); + const valHash = this.hashVal(val); + return Buffer.concat([keyHash, valHash]); + } + + /** + * Generates a SHA-256 hash for a given string. + * + * @param {string} value - The string to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + */ + hashString(value: string): Buffer { + return this.sha256([Buffer.from(value)]); + } + + /** + * Generates a hash for a 64-bit unsigned integer. + * + * @param {bigint} n - The 64-bit unsigned integer to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + */ + hashU64(n: bigint): Buffer { + const buf = Buffer.allocUnsafe(10); + let i = 0; + while (true) { + const byte = Number(n & BigInt(0x7f)); + n >>= BigInt(7); + if (n === BigInt(0)) { + buf[i] = byte; + break; + } else { + buf[i] = byte | 0x80; + ++i; + } + } + return this.hashBytes(buf.subarray(0, i + 1)); + } + + /** + * Generates a SHA-256 hash for an array of elements. + * + * @param {Array} elements - The array of elements to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + */ + hashArray(elements: Array): Buffer { + return this.sha256(elements.map(this.hashVal)); + } + + /** + * Generates a hash for a given value. + * + * @param {string | Buffer | BigInt | number | Array} val - The value to hash. + * @returns {Buffer} - The resulting hash as a Buffer. + * @throws {Error} - If the value type is unsupported. + */ + hashVal(val: string | Buffer | BigInt | number | Array): Buffer { + if (typeof val === 'string') { + return utils.hashString(val); + } else if (Buffer.isBuffer(val)) { + return utils.hashBytes(val); + } else if (typeof val === 'bigint' || typeof val === 'number') { + return utils.hashU64(BigInt(val)); + } else if (Array.isArray(val)) { + return utils.hashArray(val); + } else { + throw new Error(`Unsupported value type for hashing: ${typeof val}`); + } + } + + /** + * Computes the SHA-256 hash of the given buffer. + * + * @param value - The buffer to hash. + * @returns The SHA-256 hash of the input buffer. + */ + hashBytes(value: Buffer): Buffer { + return this.sha256([value]); + } + + /** + * Computes the SHA-256 hash of the provided array of Buffer chunks. + * + * @param {Array} chunks - An array of Buffer objects to be hashed. + * @returns {Buffer} - The resulting SHA-256 hash as a Buffer. + */ + sha256(chunks: Array): Buffer { + const hasher = js_sha256.sha256.create(); + chunks.forEach((chunk) => hasher.update(chunk)); + return Buffer.from(hasher.arrayBuffer()); + } + + /** + * Converts a hexadecimal string to a Buffer. + * + * @param hex - The hexadecimal string to convert. + * @returns A Buffer containing the binary data represented by the hexadecimal string. + */ + blobFromHex(hex: string): Buffer { + return Buffer.from(hex, 'hex'); + } + + /** + * Converts a binary blob (Buffer) to a hexadecimal string. + * + * @param {Buffer} blob - The binary data to be converted. + * @returns {string} The hexadecimal representation of the binary data. + */ + blobToHex(blob: Buffer): string { + return blob.toString('hex'); + } + + /** + * Decodes a given CBOR-encoded buffer. + * + * @param buffer - The CBOR-encoded buffer to decode. + * @returns The decoded data. + */ + cborDecode(buffer: Buffer): unknown { + const res = decode(buffer); + return res; + } + + /** + * Generates a Buffer containing the domain IC request string. + * + * @returns {Buffer} A Buffer object initialized with the string '\x0Aic-request'. + */ + getDomainICRequest(): Buffer { + return Buffer.from('\x0Aic-request'); + } + + /** + * Combines the domain IC request buffer with the provided message ID buffer to create signature data. + * + * @param {Buffer} messageId - The buffer containing the message ID. + * @returns {Buffer} - The concatenated buffer containing the domain IC request and the message ID. + */ + makeSignatureData(messageId: Buffer): Buffer { + return Buffer.concat([this.getDomainICRequest(), messageId]); + } + + /** + * Generates a read state object from an HTTP canister update. + * + * @param {HttpCanisterUpdate} update - The HTTP canister update object. + * @returns {ReadState} The read state object containing the sender, paths, and ingress expiry. + */ + makeReadStateFromUpdate(update: HttpCanisterUpdate): ReadState { return { - pub: keys.pub, - prv: keys.prv, + sender: update.sender, + paths: [[Buffer.from(REQUEST_STATUS), this.generateHttpCanisterUpdateId(update)]], + ingress_expiry: update.ingress_expiry, + }; + } + + /** + * Generates a representation-independent hash for an HTTP read state object. + * + * @param {ReadState} readState - The HTTP read state object. + * @returns {Buffer} - The hash of the read state object. + */ + HttpReadStateRepresentationIndependentHash(readState: ReadState): Buffer { + return this.hashOfMap({ + request_type: RequestType.READ_STATE, + ingress_expiry: readState.ingress_expiry, + paths: readState.paths, + sender: readState.sender, + }); + } + + /** + * Extracts the recipient information from the provided ICP transaction data. + * + * @param {IcpTransactionData} icpTransactionData - The ICP transaction data containing the receiver's address and amount. + * @returns {Recipient[]} An array containing a single recipient object with the receiver's address and amount. + */ + getRecipients(icpTransactionData: IcpTransactionData): Recipient { + return { + address: icpTransactionData.receiverAddress, + amount: icpTransactionData.amount, + }; + } + + getTransactionSignature(signatureMap: Map, update: HttpCanisterUpdate): Signatures | undefined { + return signatureMap.get(this.blobToHex(this.makeSignatureData(this.generateHttpCanisterUpdateId(update)))); + } + + getReadStateSignature(signatureMap: Map, readState: ReadState): Signatures | undefined { + return signatureMap.get( + this.blobToHex(this.makeSignatureData(this.HttpReadStateRepresentationIndependentHash(readState))) + ); + } + + getMetaData(memo: number | BigInt): { metaData: IcpMetadata; ingressEndTime: number | BigInt } { + const currentTime = Date.now() * 1000000; + const ingressStartTime = currentTime; + const ingressEndTime = ingressStartTime + 5 * 60 * 1000000000; // 5 mins in nanoseconds + const metaData: IcpMetadata = { + created_at_time: currentTime, + memo: memo, + ingress_start: ingressStartTime, + ingress_end: ingressEndTime, }; + return { metaData, ingressEndTime }; } } diff --git a/modules/sdk-coin-icp/src/ticp.ts b/modules/sdk-coin-icp/src/ticp.ts index bdbcfdf4d42..48712201ab8 100644 --- a/modules/sdk-coin-icp/src/ticp.ts +++ b/modules/sdk-coin-icp/src/ticp.ts @@ -30,13 +30,6 @@ export class Ticp extends Icp { return 'ticp'; } - /** - * Identifier for the blockchain family - */ - getFamily(): string { - return 'ticp'; - } - getBaseFactor(): number { return Math.pow(10, this._staticsCoin.decimalPlaces); } diff --git a/modules/sdk-coin-icp/test/resources/icp.ts b/modules/sdk-coin-icp/test/resources/icp.ts new file mode 100644 index 00000000000..8bf72aab23c --- /dev/null +++ b/modules/sdk-coin-icp/test/resources/icp.ts @@ -0,0 +1,266 @@ +import { IcpMetadata, OperationType } from '../../src/lib/iface'; + +export const accounts = { + account1: { + secretKey: 'c5bccb8f471c5c9eb6483aa77ee4b700003b1e12df430a24d93238eb378b968b', + publicKey: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + account2: { + secretKey: '73312c28d0d455b6a29a9a66811ffda94f3db6bfd57bf5c2bed917ee5928e15f', + publicKey: + '044e01707f70f6ad8d9f79e5f2c2f0bac5e91520e5e2491354c6c7827b59d44148847f9180ac9679a6ce66f69c330551a99f8f9b7419c437705602a54c258a9dfe', + address: 'c3d30f404955975adaba89f2e1ebc75c1f44a6a204578afce8f3780d64fe252e', + }, + account3: { + publicKey: + '042281378584012843130dce9b19002f88a949f237397e2f6cda2db1392d54f6345faaf51c384fbfe4e8f67eb12fdb53732d2ddfe7470f9310a0bf824dad3f6b1b', + secretKey: '7b4de3d8cc3e312c70f674b52f11818205546ca7036c8071997c46e429160dc3', + address: '50b59c953c9412823ada13c485656f853ec65cb58f164756429af53f06d3ab5f', + }, + account4: { + secretKey: 'c71d2779709061cc991b58bd79b0080cc125acb98b28c71ac5d63bca62e2b742', + publicKey: + '045b340975daf07887df1f32689dad303cb3e2869939d82f9225a79b0a2e56621f0c773070dc6316b36b796e7c92334c6897c9179b75efbd7a78c149f4b7a15cd9', + address: '8812eef6cf88b86ccf8d3e1b5d4aa3011025ec0c014aece4e8e9bdb02151392c', + }, + account5: { + secretKey: '8d08c0393b707cd90c37213025fe7ed13c05b267d946ca1b6e0fd3b0e47ec188', + publicKey: + '04c8e66bf2e02f15ebe8da05b74d105b54cde5114f13d4afdec8afad6aaeb621bacab8c119821ef079545413cb26ef71dd8ab681c0fcce6085648b3fe08d3cd109', + address: '6f1cd9940598e205b0affacff7fcdafa81700cd7b2d0c25f15803b955a12f100', + }, + account6: { + secretKey: '8d08c0393b707cd90c37213025fe7ed13c05b267d946ca1b6e0fd3b0e47ec188', + publicKey: '02ad010ce68b75266c723bf25fbe3a0c48eb29f14b25925b06b7f5026a0f12702e', + address: '2b9b89604362e185544c8bba76cadff1a3af26e1467e8530d13743a08a52dd7b', + }, + errorsAccounts: { + account1: { + secretKey: 'not ok', + publicKey: 'not ok', + address: 'not ok', + }, + account2: { + secretKey: 'test_test', + publicKey: 'test_test', + address: 'bo__wen', + }, + account3: { + publicKey: 'invalid-public-key', + secretKey: 'invalid-private-key', + address: 'me@google.com', + }, + account4: { + secretKey: '#$%', + publicKey: '#$%', + address: '$$$', + }, + account5: { + secretKey: 'qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm', + publicKey: 'qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm', + address: 'abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz', + }, + account6: { + secretKey: '', + publicKey: '', + address: '', + }, + }, +}; + +export const IcpTransactionData = { + senderAddress: accounts.account1.address, + receiverAddress: accounts.account2.address, + amount: '10', + fee: '-10000', + senderPublicKeyHex: accounts.account1.publicKey, + memo: 1740638136656000000, + transactionType: OperationType.TRANSACTION, + expiryTime: Date.now() * 1000_000 + 5 * 60 * 1000_000_000, +}; + +export const rawTransaction = { + outputAmount: '10', + inputAmount: '10', + spendAmount: '10', + fee: '-10000', + externalOutputs: [ + { + amount: '10', + address: accounts.account2.address, + }, + ], + type: OperationType.TRANSACTION, + address: accounts.account1.address, + senderKey: accounts.account1.publicKey, + seqno: 1740638136656000000, + spendAmountString: '10', + id: '5jTEPuDcMCeEgp1iyEbNBKsnhYz4F4c1EPDtRmxm3wCw', + expiryTime: Date.now() * 1000_000 + 5 * 60 * 1000_000_000, +}; + +export const metaData: IcpMetadata = { + created_at_time: 1740739880079000000, + ingress_end: 1740740180079000000, + ingress_start: 1740739880079000000, + memo: 1234, +}; + +export const payloadsData = { + payloads: [ + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573742dd9527902e38bc015d4f5521e680b29d1ebc5b4fe24dd5515e2abe99097f0b1', + signature_type: 'ecdsa', + }, + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573742adff4e1c4b8b725bd4accbaf80cd2b180b322bfc450ec00d14aa315c9a4e324', + signature_type: 'ecdsa', + }, + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d7265717565737476265b535aeeda1b30f9a276a62e9247c9288d518349d68b504e9db5f9fd7563', + signature_type: 'ecdsa', + }, + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d72657175657374bb6cfef054ce8ce0a54593f7eb78bb089dc14673e1556afd20dd9534d29aa2f7', + signature_type: 'ecdsa', + }, + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573741c174f275615e80d7280542bf373e2ecfa59c3a1d87475feed0a97203fb22f37', + signature_type: 'ecdsa', + }, + { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573741814112eb6162e3dc5cc6a5a87c9ec2a6578e762059ec7510591aad208e7cded', + signature_type: 'ecdsa', + }, + ], + unsigned_transaction: + 'b90002677570646174657381826b5452414e53414354494f4eb900056b63616e69737465725f69644a000000000000000201016b6d6574686f645f6e616d656773656e645f70626361726758400a0308d20912040a02080a1a0308904e2a220a20c3d30f404955975adaba89f2e1ebc75c1f44a6a204578afce8f3780d64fe252e3a0a088084dcb3abb69694186673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a026e696e67726573735f6578706972791b000000000000000070696e67726573735f6578706972696573831b182859ea979462001b18285a06882312001b18285a2278b1c200', +}; + +export const signatures = [ + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573742dd9527902e38bc015d4f5521e680b29d1ebc5b4fe24dd5515e2abe99097f0b1', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + '11d903fe529788a2202a261568066371e2022ddb339379368e19567473b3c2d7a88e032684652109ec8d9ef6b6600c479620ca690b26ecf07678b3ee307d1375', + }, + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573742adff4e1c4b8b725bd4accbaf80cd2b180b322bfc450ec00d14aa315c9a4e324', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + 'b50df90e4c94e45d4bd7117d98380d104f19cf7053814887acfe4d6ad24b08f8735473b00e5740beef2e675d98764dc22ab44c653ecf65281cc46601d2802eb5', + }, + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d7265717565737476265b535aeeda1b30f9a276a62e9247c9288d518349d68b504e9db5f9fd7563', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + '005e67fcb5f5937b969b64eca79077030e7a0e9841dc6babca4211167c32799235b16823f37ba8b9431293705ac4b5e62c6fa18e0ea265a121f58d368295d45c', + }, + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d72657175657374bb6cfef054ce8ce0a54593f7eb78bb089dc14673e1556afd20dd9534d29aa2f7', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + '7e995be0c48d6e45c7fb671e53da580023bcca0346b346c7374d379d5d98b0205a304e9f9653694239c0e54d39503dbab5b0d3bcc64ca5f03f37de6a4300b6bd', + }, + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573741c174f275615e80d7280542bf373e2ecfa59c3a1d87475feed0a97203fb22f37', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + '9ee8331ab5b3cab1047b34540c5f74b89d3bb754cef793c09a7e728b781609531a84796c1e6f8474014f75c4918d68eb314ee487f6c64878a039cf3fe618e184', + }, + { + signing_payload: { + account_identifier: { + address: '0af815da8259ba8bb3d34fbfb2ac730f07a1adc81438d40d667d91b408b25f2f', + }, + hex_bytes: '0a69632d726571756573741814112eb6162e3dc5cc6a5a87c9ec2a6578e762059ec7510591aad208e7cded', + signature_type: 'ecdsa', + }, + signature_type: 'ecdsa', + public_key: { + hex_bytes: + '042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d4', + curve_type: 'secp256k1', + }, + hex_bytes: + '4ae4da61c3ef1b04e32fbb1b7c0b79ad89bb2b45501dbe2b84a4216df90a1038800e8e477e3eb52f1b91acfd14972279544ca940d5853fc7dcb2bc12dd0428ab', + }, +]; + +export const signedTransaction = + 'b9000168726571756573747381826b5452414e53414354494f4e83b9000266757064617465b9000367636f6e74656e74b900066c726571756573745f747970656463616c6c6b63616e69737465725f69644a000000000000000201016b6d6574686f645f6e616d656773656e645f70626361726758400a0308d20912040a02080a1a0308904e2a220a20c3d30f404955975adaba89f2e1ebc75c1f44a6a204578afce8f3780d64fe252e3a0a088084dcb3abb69694186673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a026e696e67726573735f6578706972791b182859ea979462006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f736967584011d903fe529788a2202a261568066371e2022ddb339379368e19567473b3c2d7a88e032684652109ec8d9ef6b6600c479620ca690b26ecf07678b3ee307d13756a726561645f7374617465b9000367636f6e74656e74b900046c726571756573745f747970656a726561645f73746174656673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a0265706174687381824e726571756573745f73746174757358202dd9527902e38bc015d4f5521e680b29d1ebc5b4fe24dd5515e2abe99097f0b16e696e67726573735f6578706972791b182859ea979462006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f7369675840b50df90e4c94e45d4bd7117d98380d104f19cf7053814887acfe4d6ad24b08f8735473b00e5740beef2e675d98764dc22ab44c653ecf65281cc46601d2802eb5b9000266757064617465b9000367636f6e74656e74b900066c726571756573745f747970656463616c6c6b63616e69737465725f69644a000000000000000201016b6d6574686f645f6e616d656773656e645f70626361726758400a0308d20912040a02080a1a0308904e2a220a20c3d30f404955975adaba89f2e1ebc75c1f44a6a204578afce8f3780d64fe252e3a0a088084dcb3abb69694186673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a026e696e67726573735f6578706972791b18285a06882312006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f7369675840005e67fcb5f5937b969b64eca79077030e7a0e9841dc6babca4211167c32799235b16823f37ba8b9431293705ac4b5e62c6fa18e0ea265a121f58d368295d45c6a726561645f7374617465b9000367636f6e74656e74b900046c726571756573745f747970656a726561645f73746174656673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a0265706174687381824e726571756573745f737461747573582076265b535aeeda1b30f9a276a62e9247c9288d518349d68b504e9db5f9fd75636e696e67726573735f6578706972791b18285a06882312006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f73696758407e995be0c48d6e45c7fb671e53da580023bcca0346b346c7374d379d5d98b0205a304e9f9653694239c0e54d39503dbab5b0d3bcc64ca5f03f37de6a4300b6bdb9000266757064617465b9000367636f6e74656e74b900066c726571756573745f747970656463616c6c6b63616e69737465725f69644a000000000000000201016b6d6574686f645f6e616d656773656e645f70626361726758400a0308d20912040a02080a1a0308904e2a220a20c3d30f404955975adaba89f2e1ebc75c1f44a6a204578afce8f3780d64fe252e3a0a088084dcb3abb69694186673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a026e696e67726573735f6578706972791b18285a2278b1c2006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f73696758409ee8331ab5b3cab1047b34540c5f74b89d3bb754cef793c09a7e728b781609531a84796c1e6f8474014f75c4918d68eb314ee487f6c64878a039cf3fe618e1846a726561645f7374617465b9000367636f6e74656e74b900046c726571756573745f747970656a726561645f73746174656673656e646572581dd5fc1dc4d74d4aa35d81cf345533d20548113412d32fffdcece2f68a0265706174687381824e726571756573745f73746174757358201c174f275615e80d7280542bf373e2ecfa59c3a1d87475feed0a97203fb22f376e696e67726573735f6578706972791b18285a2278b1c2006d73656e6465725f7075626b6579d84058583056301006072a8648ce3d020106052b8104000a034200042ab77b959e28c4fa47fa8fb9e57cec3d66df5684d076ac2e4c5f28fd69a23dd31a59f908c8add51eab3530b4ac5d015166eaf2198c52fa9a8df7cfaeb8fdb7d46a73656e6465725f73696758404ae4da61c3ef1b04e32fbb1b7c0b79ad89bb2b45501dbe2b84a4216df90a1038800e8e477e3eb52f1b91acfd14972279544ca940d5853fc7dcb2bc12dd0428ab'; diff --git a/modules/sdk-coin-icp/test/unit/getBuilderFactory.ts b/modules/sdk-coin-icp/test/unit/getBuilderFactory.ts new file mode 100644 index 00000000000..082badb5939 --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/getBuilderFactory.ts @@ -0,0 +1,6 @@ +import { TransactionBuilderFactory } from '../../src'; +import { coins } from '@bitgo/statics'; + +export const getBuilderFactory = (coin: string): TransactionBuilderFactory => { + return new TransactionBuilderFactory(coins.get(coin)); +}; diff --git a/modules/sdk-coin-icp/test/unit/icp.ts b/modules/sdk-coin-icp/test/unit/icp.ts index ffe5f023453..a84ef3650a0 100644 --- a/modules/sdk-coin-icp/test/unit/icp.ts +++ b/modules/sdk-coin-icp/test/unit/icp.ts @@ -37,7 +37,7 @@ describe('Internet computer', function () { icp.supportsTss().should.equal(true); ticp.getChain().should.equal('ticp'); - ticp.getFamily().should.equal('ticp'); + ticp.getFamily().should.equal('icp'); ticp.getFullName().should.equal('Testnet Internet Computer'); ticp.getBaseFactor().should.equal(1e8); icp.supportsTss().should.equal(true); @@ -76,7 +76,7 @@ describe('Internet computer', function () { it('should throw an error when invalid public key is provided', async function () { await basecoin .getAddressFromPublicKey(invalidPublicKey) - .should.be.rejectedWith(`Public Key is not in a valid Hex Encoded Format`); + .should.be.rejectedWith(`Invalid hex-encoded public key format.`); }); it('should return valid address from a valid hex encoded public key', async function () { @@ -87,7 +87,7 @@ describe('Internet computer', function () { it('should throw an error when invalid public key is provided', async function () { await utils .getAddressFromPublicKey(invalidPublicKey) - .should.be.rejectedWith(`Public Key is not in a valid Hex Encoded Format`); + .should.be.rejectedWith(`Invalid hex-encoded public key format.`); }); }); describe('Generate wallet key pair: ', () => { diff --git a/modules/sdk-coin-icp/test/unit/keyPair.ts b/modules/sdk-coin-icp/test/unit/keyPair.ts new file mode 100644 index 00000000000..50b32f03f83 --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/keyPair.ts @@ -0,0 +1,118 @@ +import should from 'should'; +import { KeyPair } from '../../src/lib/keyPair'; +import { randomBytes } from 'crypto'; + +describe('ICP KeyPair', () => { + describe('constructor', () => { + it('should generate a key pair with a random seed when no source is provided', () => { + const keyPair = new KeyPair(); + should.exist(keyPair); + const publicKey = keyPair.getKeys().pub; + const privateKey = keyPair.getKeys().prv; + should.exist(publicKey); + should.exist(privateKey); + publicKey.should.be.a.String(); + if (privateKey) { + privateKey.should.be.a.String(); + } + }); + + it('should generate a key pair from a given seed', () => { + const seed = randomBytes(32); + const keyPair = new KeyPair({ seed }); + should.exist(keyPair); + const publicKey = keyPair.getKeys().pub; + const privateKey = keyPair.getKeys().prv; + should.exist(publicKey); + should.exist(privateKey); + publicKey.should.be.a.String(); + if (privateKey) { + privateKey.should.be.a.String(); + } + }); + + it('should generate a key pair from a public key', () => { + const tempKeyPair = new KeyPair(); + const publicKey = tempKeyPair.getKeys().pub; + const keyPair = new KeyPair({ pub: publicKey }); + + should.exist(keyPair); + should.exist(keyPair.getKeys().pub); + should.equal(keyPair.getKeys().pub, publicKey); + }); + + it('should generate different key pairs for different seeds', () => { + const seed1 = randomBytes(32); + const seed2 = randomBytes(32); + const keyPair1 = new KeyPair({ seed: seed1 }); + const keyPair2 = new KeyPair({ seed: seed2 }); + + should.notEqual(keyPair1.getKeys().pub, keyPair2.getKeys().pub); + should.notEqual(keyPair1.getKeys().prv, keyPair2.getKeys().prv); + }); + + it('should generate the same key pair for the same seed', () => { + const seed = randomBytes(32); + const keyPair1 = new KeyPair({ seed }); + const keyPair2 = new KeyPair({ seed }); + + should.equal(keyPair1.getKeys().pub, keyPair2.getKeys().pub); + should.equal(keyPair1.getKeys().prv, keyPair2.getKeys().prv); + }); + }); + + describe('KeyPair getKeys()', () => { + it('should return valid public and private keys for a randomly generated key pair', () => { + const keyPair = new KeyPair(); + const keys = keyPair.getKeys(); + + should.exist(keys); + should.exist(keys.pub); + should.exist(keys.prv); + keys.pub.should.be.a.String(); + keys.pub.length.should.be.greaterThan(0); + if (keys.prv) { + keys.prv.should.be.a.String(); + keys.prv.length.should.be.greaterThan(0); + } + }); + + it('should return valid public and private keys for a key pair generated with a seed', () => { + const seed = randomBytes(32); + const keyPair = new KeyPair({ seed }); + const keys = keyPair.getKeys(); + + should.exist(keys); + should.exist(keys.pub); + should.exist(keys.prv); + keys.pub.should.be.a.String(); + if (keys.prv) { + keys.prv.should.be.a.String(); + } + }); + + it('should return only a public key when a key pair is generated from a public key', () => { + const tempKeyPair = new KeyPair(); + const publicKey = tempKeyPair.getKeys().pub; + const keyPair = new KeyPair({ pub: publicKey }); + const keys = keyPair.getKeys(); + + should.exist(keys); + should.exist(keys.pub); + should.equal(keys.pub, publicKey); + should.not.exist(keys.prv); + }); + + it('should generate consistent keys for the same seed', () => { + const seed = randomBytes(32); + const keyPair1 = new KeyPair({ seed }); + const keyPair2 = new KeyPair({ seed }); + + const keys1 = keyPair1.getKeys(); + const keys2 = keyPair2.getKeys(); + + should.equal(keys1.pub, keys2.pub); + should.equal(keys1.prv, keys2.prv); + }); + }); +}); diff --git a/modules/sdk-coin-icp/test/unit/transaction.ts b/modules/sdk-coin-icp/test/unit/transaction.ts new file mode 100644 index 00000000000..2d7e298e6fb --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/transaction.ts @@ -0,0 +1,93 @@ +import { Transaction } from '../../src'; +import { coins } from '@bitgo/statics'; +import assert from 'assert'; +import should from 'should'; +import { Utils } from '../../src/lib/utils'; +import { InvalidTransactionError, TransactionType as BitGoTransactionType } from '@bitgo/sdk-core'; +import { rawTransaction, accounts } from '../resources/icp'; + +describe('ICP Transaction', () => { + let tx: Transaction; + let utils: Utils; + let localRawTransaction: any; + const config = coins.get('ticp'); + + beforeEach(() => { + utils = new Utils(); + tx = new Transaction(config, utils); + localRawTransaction = JSON.parse(JSON.stringify(rawTransaction)); + }); + + describe('empty transaction', () => { + it('should throw an empty transaction error', () => { + assert.throws( + () => tx.toBroadcastFormat(), + (err) => err instanceof InvalidTransactionError && err.message === 'Empty transaction', + 'Expected an InvalidTransactionError with message "Empty transaction"' + ); + assert.throws( + () => tx.toJson(), + (err) => err instanceof InvalidTransactionError && err.message === 'Empty transaction', + 'Expected an InvalidTransactionError with message "Empty transaction"' + ); + }); + }); + + describe('from raw transaction', () => { + it('build a json transaction from raw hex', async () => { + tx.fromRawTransaction(JSON.stringify(localRawTransaction)); + const json = tx.toJson(); + should.equal(json.expirationTime, localRawTransaction.expiryTime); + should.equal(json.memo, localRawTransaction.seqno); + should.equal(json.feeAmount, '-10000'); + should.equal(json.sender, localRawTransaction.address); + should.equal(json.recipient, localRawTransaction.externalOutputs[0].address); + should.equal(json.type, BitGoTransactionType.Send); + should.equal(json.senderPublicKey, accounts.account1.publicKey); + }); + + it('should fail when memo is passed as alphanumeric', async () => { + (localRawTransaction as any).seqno = 'abc123'; + assert.throws( + () => tx.fromRawTransaction(JSON.stringify(localRawTransaction)), + (err) => err instanceof InvalidTransactionError && err.message === 'Invalid raw transaction', + 'Expected an InvalidTransactionError with message "Invalid raw transaction"' + ); + }); + + it('should fail when memo is passed as string', async () => { + (localRawTransaction as any).seqno = 'abc'; + assert.throws( + () => tx.fromRawTransaction(JSON.stringify(localRawTransaction)), + (err) => err instanceof InvalidTransactionError && err.message === 'Invalid raw transaction', + 'Expected an InvalidTransactionError with message "Invalid raw transaction"' + ); + }); + }); + + describe('Explain', () => { + it('explain transaction', async () => { + tx.fromRawTransaction(JSON.stringify(localRawTransaction)); + const explain = tx.explainTransaction(); + + explain.outputAmount.should.equal('10'); + explain.outputs[0].amount.should.equal('10'); + explain.outputs[0].address.should.equal(accounts.account2.address); + explain.fee.fee.should.equal('-10000'); + explain.changeAmount.should.equal('0'); + if (explain.displayOrder !== undefined) { + explain.displayOrder.should.deepEqual([ + 'id', + 'outputAmount', + 'changeAmount', + 'outputs', + 'changeOutputs', + 'fee', + ]); + } + if (explain.type !== undefined) { + explain.type.should.equal(BitGoTransactionType.Send); + } + }); + }); +}); diff --git a/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionBuilder.ts b/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionBuilder.ts new file mode 100644 index 00000000000..a7fb381dc91 --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/transactionBuilder/transactionBuilder.ts @@ -0,0 +1,75 @@ +import should from 'should'; +import { getBuilderFactory } from '../getBuilderFactory'; +import * as testData from '../../resources/icp'; +import sinon from 'sinon'; + +describe('ICP Transaction Builder', async () => { + const factory = getBuilderFactory('ticp'); + let txBuilder: any; + let txn: any; + + beforeEach(async function () { + txBuilder = factory.getTransferBuilder(); + sinon.stub(txBuilder._utils, 'getMetaData').returns({ + metaData: testData.metaData, + ingressEndTime: testData.metaData.ingress_end, + }); + + txBuilder.sender(testData.accounts.account1.address, testData.accounts.account1.publicKey); + txBuilder.receiverId(testData.accounts.account2.address); + txBuilder.amount('10'); + txBuilder.memo(testData.metaData.memo); + + await txBuilder.build(); + txn = txBuilder.transaction; + }); + + afterEach(function () { + sinon.restore(); + }); + + it('start and build a transfer tx', async () => { + const icpTransaction = txBuilder.transaction.icpTransaction; + const payloadsData = txBuilder.transaction.payloadsData; + should.equal(icpTransaction.metadata.memo, testData.metaData.memo); + should.equal(icpTransaction.operations[0].account.address, testData.accounts.account1.address); + should.equal(icpTransaction.operations[1].account.address, testData.accounts.account2.address); + should.equal(icpTransaction.operations[0].amount.value, '-10'); + should.equal(icpTransaction.operations[1].amount.value, '10'); + should.equal(icpTransaction.operations[2].amount.value, '-10000'); + should.equal(icpTransaction.public_keys[0].hex_bytes, testData.accounts.account1.publicKey); + payloadsData.unsigned_transaction.should.be.a.String(); + payloadsData.payloads.should.be.an.Array(); + should.equal(payloadsData.unsigned_transaction, testData.payloadsData.unsigned_transaction); + should.deepEqual(payloadsData.payloads, testData.payloadsData.payloads); + }); + + it('should fail to build a txn without sender', async () => { + const txBuilder = factory.getTransferBuilder(); + txBuilder.receiverId(testData.accounts.account2.address); + txBuilder.amount('10'); + txBuilder.memo(123456); + await txBuilder.build().should.rejectedWith('sender is required before building'); + }); + + it('should fail to build a txn without amount', async () => { + const txBuilder = factory.getTransferBuilder(); + txBuilder.sender(testData.accounts.account1.address, testData.accounts.account1.publicKey); + txBuilder.receiverId(testData.accounts.account2.address); + txBuilder.memo(123456); + await txBuilder.build().should.rejectedWith('amount is required before building'); + }); + + it('should build a signed txn and give txn in broadcast format', async () => { + txn.addSignature(testData.signatures); + txBuilder.sign({ key: testData.accounts.account1.secretKey }); + const signedTxn = txBuilder.transaction.signedTransaction; + signedTxn.should.be.a.String(); + should.equal(signedTxn, testData.signedTransaction); + const broadcastTxn = txBuilder.transaction.toBroadcastFormat(); + broadcastTxn.should.be.a.String(); + const broadcastTxnObj = JSON.parse(broadcastTxn); + should.equal(broadcastTxnObj.signed_transaction, signedTxn); + should.equal(broadcastTxnObj.network_identifier.network, '00000000000000020101'); + }); +}); diff --git a/modules/sdk-coin-icp/test/unit/utils.ts b/modules/sdk-coin-icp/test/unit/utils.ts new file mode 100644 index 00000000000..9db11983c63 --- /dev/null +++ b/modules/sdk-coin-icp/test/unit/utils.ts @@ -0,0 +1,194 @@ +import should from 'should'; +import utils from '../../src/lib/utils'; +import { accounts, IcpTransactionData } from '../resources/icp'; +import { encode } from 'cbor-x'; +import { randomBytes } from 'crypto'; + +describe('utils', () => { + describe('isValidAddress()', () => { + it('should validate addresses correctly', () => { + should.equal(utils.isValidAddress(accounts.account1.address), true); + should.equal(utils.isValidAddress(accounts.account2.address), true); + should.equal(utils.isValidAddress(accounts.account3.address), true); + should.equal(utils.isValidAddress(accounts.account4.address), true); + should.equal(utils.isValidAddress(accounts.account5.address), true); + should.equal(utils.isValidAddress(accounts.account6.address), true); + }); + + it('should invalidate wrong addresses correctly', () => { + should.equal(utils.isValidAddress(accounts.errorsAccounts.account1.address), false); + should.equal(utils.isValidAddress(accounts.errorsAccounts.account2.address), false); + should.equal(utils.isValidAddress(accounts.errorsAccounts.account3.address), false); + should.equal(utils.isValidAddress(accounts.errorsAccounts.account4.address), false); + should.equal(utils.isValidAddress(accounts.errorsAccounts.account5.address), false); + should.equal(utils.isValidAddress(accounts.errorsAccounts.account6.address), false); + }); + }); + + describe('gasData()', () => { + it('should return correct gas data', () => { + should.equal(utils.gasData(), '-10000'); + }); + }); + + describe('isValidPublicKey()', () => { + it('should validate public key correctly', () => { + should.equal(utils.isValidPublicKey(accounts.account1.publicKey), true); + should.equal(utils.isValidPublicKey(accounts.account2.publicKey), true); + should.equal(utils.isValidPublicKey(accounts.account3.publicKey), true); + should.equal(utils.isValidPublicKey(accounts.account4.publicKey), true); + should.equal(utils.isValidPublicKey(accounts.account5.publicKey), true); + should.equal(utils.isValidPublicKey(accounts.account6.publicKey), true); + }); + + it('should invalidate public key correctly', () => { + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account1.publicKey), false); + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account2.publicKey), false); + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account3.publicKey), false); + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account4.publicKey), false); + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account5.publicKey), false); + should.equal(utils.isValidPublicKey(accounts.errorsAccounts.account6.publicKey), false); + }); + }); + + describe('cborEncode()', () => { + it('should correctly encode an object', () => { + const value = { key: 'value' }; + const expectedHex = Buffer.from(encode(value)).toString('hex'); + should.equal(utils.cborEncode(value), expectedHex); + }); + + it('should encode and decode a big number correctly', () => { + const original = { number: BigInt(1740680777458000000) }; + const encoded = encode(original); + const decoded = utils.cborDecode(encoded); + should.deepEqual(decoded, original); + }); + }); + + describe('cborDecode()', () => { + it('should correctly decode a CBOR-encoded object', () => { + const original = { key: 'value', number: 100 }; + const encoded = encode(original); + const decoded = utils.cborDecode(encoded); + should.deepEqual(decoded, original); + }); + }); + + describe('isValidLength()', () => { + it('should return true for a valid compressed public key length (66 characters)', () => { + should.equal(utils.isValidLength('a'.repeat(66)), true); + }); + }); + + describe('isValidHex()', () => { + it('should return true for a valid hexadecimal string', () => { + should.equal(utils.isValidHex('abcdef1234567890ABCDEF'), true); + }); + }); + + describe('hexToBytes()', () => { + it('should correctly convert a valid hexadecimal string to a Uint8Array', () => { + const hex = 'abcdef123456'; + const expected = new Uint8Array([0xab, 0xcd, 0xef, 0x12, 0x34, 0x56]); + should.deepEqual(utils.hexToBytes(hex), expected); + }); + }); + + describe('isValidPrivateKey()', () => { + it('should validate private key correctly', () => { + should.equal(utils.isValidPrivateKey(accounts.account1.secretKey), true); + should.equal(utils.isValidPrivateKey(accounts.account2.secretKey), true); + should.equal(utils.isValidPrivateKey(accounts.account3.secretKey), true); + should.equal(utils.isValidPrivateKey(accounts.account4.secretKey), true); + should.equal(utils.isValidPrivateKey(accounts.account5.secretKey), true); + should.equal(utils.isValidPrivateKey(accounts.account6.secretKey), true); + }); + + it('should invalidate private key correctly', () => { + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account1.secretKey), false); + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account2.secretKey), false); + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account3.secretKey), false); + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account4.secretKey), false); + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account5.secretKey), false); + should.equal(utils.isValidPrivateKey(accounts.errorsAccounts.account6.secretKey), false); + }); + }); + + describe('getAddressFromPublicKey()', () => { + it('should return the correct address for a valid public key', async () => { + const address1 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address1, accounts.account1.address); + const address2 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address2, accounts.account1.address); + const address3 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address3, accounts.account1.address); + const address4 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address4, accounts.account1.address); + const address5 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address5, accounts.account1.address); + const address6 = await utils.getAddressFromPublicKey(accounts.account1.publicKey); + should.equal(address6, accounts.account1.address); + }); + + it('should throw an error for an invalid public key', async () => { + await should(utils.getAddressFromPublicKey(accounts.errorsAccounts.account1.publicKey)).be.rejectedWith( + 'Invalid hex-encoded public key format.' + ); + }); + }); + + describe('generateKeyPair()', () => { + it('should generate a valid key pair without a seed', () => { + const keyPair = utils.generateKeyPair(); + should.exist(keyPair); + should.exist(keyPair.pub); + should.exist(keyPair.prv); + }); + + it('should generate a valid key pair with a given seed', () => { + const seed = randomBytes(32); + const keyPair = utils.generateKeyPair(seed); + should.exist(keyPair); + should.exist(keyPair.pub); + should.exist(keyPair.prv); + }); + + it('should generate different key pairs for different seeds', () => { + const seed1 = randomBytes(32); + const seed2 = randomBytes(32); + const keyPair1 = utils.generateKeyPair(seed1); + const keyPair2 = utils.generateKeyPair(seed2); + + should.notEqual(keyPair1.pub, keyPair2.pub); + should.notEqual(keyPair1.prv, keyPair2.prv); + }); + + it('should generate the same key pair for the same seed', () => { + const seed = randomBytes(32); + const keyPair1 = utils.generateKeyPair(seed); + const keyPair2 = utils.generateKeyPair(seed); + + should.equal(keyPair1.pub, keyPair2.pub); + should.equal(keyPair1.prv, keyPair2.prv); + }); + }); + + describe('validateRawTransaction()', () => { + const data = IcpTransactionData; + it('should validate icpTransactionData correctly', () => { + utils.validateRawTransaction(data); + }); + it('should throw an error for invalid expiryTime', () => { + (data.expiryTime = Date.now()), should.throws(() => utils.validateRawTransaction(data), 'Invalid expiry time'); + }); + it('should throw an error for invalid fee', () => { + data.fee = '-100'; + should.throws(() => utils.validateRawTransaction(data), 'Invalid fee value'); + }); + it('should throw an error for invalid amount', () => { + data.amount = '0'; + should.throws(() => utils.validateRawTransaction(data), 'amount cannot be less than or equal to zero'); + }); + }); +}); diff --git a/modules/sdk-coin-xtz/src/xtz.ts b/modules/sdk-coin-xtz/src/xtz.ts index 9df67aa26a5..9cd700e7896 100644 --- a/modules/sdk-coin-xtz/src/xtz.ts +++ b/modules/sdk-coin-xtz/src/xtz.ts @@ -1,20 +1,20 @@ import { BaseCoin, - BitGoBase, BaseTransactionBuilder, - KeyPair as SdkCoreKeyPair, + BitGoBase, MethodNotImplementedError, ParsedTransaction, ParseTransactionOptions, + KeyPair as SdkCoreKeyPair, SignedTransaction, + TransactionExplanation, VerifyAddressOptions, VerifyTransactionOptions, - TransactionExplanation, } from '@bitgo/sdk-core'; -import { BaseCoin as StaticsBaseCoin, CoinFamily, coins } from '@bitgo/statics'; -import BigNumber from 'bignumber.js'; import { bip32 } from '@bitgo/secp256k1'; -import { Interface, Utils, KeyPair, TransactionBuilder } from './lib'; +import { CoinFamily, coins, BaseCoin as StaticsBaseCoin } from '@bitgo/statics'; +import BigNumber from 'bignumber.js'; +import { Interface, KeyPair, TransactionBuilder, Utils } from './lib'; export class Xtz extends BaseCoin { protected readonly _staticsCoin: Readonly; @@ -170,7 +170,8 @@ export class Xtz extends BaseCoin { */ async signMessage(key: SdkCoreKeyPair, message: string | Buffer): Promise { const keyPair = new KeyPair({ prv: key.prv }); - const messageHex = message instanceof Buffer ? message.toString('hex') : Buffer.from(message).toString('hex'); + const messageHex = + message instanceof Buffer ? message.toString('hex') : Buffer.from(message as string, 'utf-8').toString('hex'); const signatureData = await Utils.sign(keyPair, messageHex); return Buffer.from(signatureData.sig); }