All files / src base_transaction.ts

93.83% Statements 152/162
85.45% Branches 94/110
96.43% Functions 27/28
93.83% Lines 152/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652                            17x             17x   17x             17x         17x 17x   17x                                                                                                       17x 17x 17x 17x 17x 17x     17x 17x   17x                         17x           667x                         667x       667x 667x         667x 667x   667x 667x 667x 667x   667x     667x 667x 667x 667x 667x       241x       224x       636x 2x     634x       21x 1x     20x       145x                 129x                                 129x       3x       3x             325x           325x       14x 14x 1x     13x 13x       1x       12x 12x         12x         12x             12x 4x     12x 2x                     12x             2x           13x   13x       4x 4x     4x 4x 4x     4x 4x         4x 4x   4x   4x                       4x       2x 2x 2x           2x                     2x 2x 2x   2x                               5x   5x       2x                 3x 1x               2x 2x               2x 2x           2x             2x 2x   2x                               2x 1x   1x     1x               8x 8x 8x               8x 8x         8x           8x 8x 3x             5x       2x       2x   2x           2x   2x       112x   112x           112x   112x 112x   112x       1x     111x 111x         111x         111x 14x                     111x       365x 365x 365x 365x   365x                 63x                       4x       4x 4x               4x 4x       4x           4x                         17x 17x       17x         17x   7x       16x         16x         17x      
/*
 * Copyright © 2019 Lisk Foundation
 *
 * See the LICENSE file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
 * no part of this software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */
import {
	getAddressAndPublicKeyFromPassphrase,
	getAddressFromPublicKey,
	hash,
	hexToBuffer,
	signData,
} from '@liskhq/lisk-cryptography';
import { validator } from '@liskhq/lisk-validator';
 
import {
	BYTESIZES,
	MAX_TRANSACTION_AMOUNT,
	UNCONFIRMED_MULTISIG_TRANSACTION_TIMEOUT,
	UNCONFIRMED_TRANSACTION_TIMEOUT,
} from './constants';
import { SignatureObject } from './create_signature_object';
import {
	convertToTransactionError,
	TransactionError,
	TransactionPendingError,
} from './errors';
import { createResponse, Status } from './response';
import * as schemas from './schema';
import { Account, TransactionJSON } from './transaction_types';
import {
	getId,
	validateSenderIdAndPublicKey,
	validateSignature,
	verifyBalance,
	verifyMultiSignatures,
	verifySecondSignature,
	verifySenderPublicKey,
} from './utils';
 
export interface TransactionResponse {
	readonly id: string;
	readonly status: Status;
	readonly errors: ReadonlyArray<TransactionError>;
}
 
export interface StateStoreGetter<T> {
	get(key: string): Promise<T>;
	find(func: (item: T) => boolean): T | undefined;
}
 
export interface StateStoreDefaultGetter<T> {
	getOrDefault(key: string): Promise<T>;
}
 
export interface StateStoreSetter<T> {
	set(key: string, value: T): void;
}
 
export interface StateStoreTransactionGetter<T> {
	get(key: string): T;
	find(func: (item: T) => boolean): T | undefined;
}
 
export interface StateStore {
	readonly account: StateStoreGetter<Account> &
		StateStoreDefaultGetter<Account> &
		StateStoreSetter<Account>;
	readonly transaction: StateStoreTransactionGetter<TransactionJSON>;
}
 
export interface StateStoreCache<T> {
	cache(
		filterArray: ReadonlyArray<{ readonly [key: string]: string }>,
	): Promise<ReadonlyArray<T>>;
}
 
export interface StateStorePrepare {
	readonly account: StateStoreCache<Account>;
	readonly transaction: StateStoreCache<TransactionJSON>;
}
 
export enum MultisignatureStatus {
	UNKNOWN = 0,
	NONMULTISIGNATURE = 1,
	PENDING = 2,
	READY = 3,
	FAIL = 4,
}
 
export const ENTITY_ACCOUNT = 'account';
export const ENTITY_TRANSACTION = 'transaction';
 
export abstract class BaseTransaction {
	public readonly blockId?: string;
	public readonly height?: number;
	public readonly confirmations?: number;
	public readonly signatures: string[];
	public readonly timestamp: number;
	public readonly type: number;
	public readonly containsUniqueData?: boolean;
	public readonly asset: object;
	public fee: bigint;
	public receivedAt?: Date;
 
	public static TYPE: number;
	public static FEE = '0';
 
	protected _id?: string;
	protected _senderPublicKey?: string;
	protected _signature?: string;
	protected _signSignature?: string;
	protected _multisignatureStatus: MultisignatureStatus =
		MultisignatureStatus.UNKNOWN;
	protected _networkIdentifier: string;
 
	protected abstract validateAsset(): ReadonlyArray<TransactionError>;
	protected abstract applyAsset(
		store: StateStore,
	): Promise<ReadonlyArray<TransactionError>>;
	protected abstract undoAsset(
		store: StateStore,
	): Promise<ReadonlyArray<TransactionError>>;
 
	public constructor(rawTransaction: unknown) {
		const tx = (typeof rawTransaction === 'object' && rawTransaction !== null
			? rawTransaction
			: {}) as Partial<TransactionJSON>;
 
		this.fee = BigInt((this.constructor as typeof BaseTransaction).FEE);
		this.type =
			typeof tx.type === 'number'
				? tx.type
				: (this.constructor as typeof BaseTransaction).TYPE;
 
		this._id = tx.id;
		this._senderPublicKey = tx.senderPublicKey || '';
 
		this._signature = tx.signature;
		this.signatures = (tx.signatures as string[]) || [];
		this._signSignature = tx.signSignature;
		this._networkIdentifier = tx.networkIdentifier || '';
 
		this.timestamp = typeof tx.timestamp === 'number' ? tx.timestamp : 0;
 
		// Additional data not related to the protocol
		this.confirmations = tx.confirmations;
		this.blockId = tx.blockId;
		this.height = tx.height;
		this.receivedAt = tx.receivedAt ? new Date(tx.receivedAt) : undefined;
		this.asset = tx.asset || {};
	}
 
	public get id(): string {
		return this._id || 'incalculable-id';
	}
 
	public get senderId(): string {
		return getAddressFromPublicKey(this.senderPublicKey);
	}
 
	public get senderPublicKey(): string {
		if (!this._senderPublicKey) {
			throw new Error('senderPublicKey is required to be set before use');
		}
 
		return this._senderPublicKey;
	}
 
	public get signature(): string {
		if (!this._signature) {
			throw new Error('signature is required to be set before use');
		}
 
		return this._signature;
	}
 
	public get signSignature(): string | undefined {
		return this._signSignature;
	}
 
	/**
	 * This method is using private versions of _id, _senderPublicKey and _signature
	 * as we should allow for it to be called at any stage of the transaction construction
	 */
 
	public toJSON(): TransactionJSON {
		const transaction = {
			id: this._id,
			blockId: this.blockId,
			height: this.height,
			confirmations: this.confirmations,
			type: this.type,
			timestamp: this.timestamp,
			senderPublicKey: this._senderPublicKey || '',
			senderId: this._senderPublicKey ? this.senderId : '',
			fee: this.fee.toString(),
			signature: this._signature,
			signSignature: this.signSignature ? this.signSignature : undefined,
			signatures: this.signatures,
			asset: this.assetToJSON(),
			receivedAt: this.receivedAt ? this.receivedAt.toISOString() : undefined,
		};
 
		return transaction;
	}
 
	public stringify(): string {
		return JSON.stringify(this.toJSON());
	}
 
	public isReady(): boolean {
		return (
			this._multisignatureStatus === MultisignatureStatus.READY ||
			this._multisignatureStatus === MultisignatureStatus.NONMULTISIGNATURE
		);
	}
 
	public getBytes(): Buffer {
		const transactionBytes = Buffer.concat([
			this.getBasicBytes(),
			this._signature ? hexToBuffer(this._signature) : Buffer.alloc(0),
			this._signSignature ? hexToBuffer(this._signSignature) : Buffer.alloc(0),
		]);
 
		return transactionBytes;
	}
 
	public validate(): TransactionResponse {
		const errors = [...this._validateSchema(), ...this.validateAsset()];
		if (errors.length > 0) {
			return createResponse(this.id, errors);
		}
 
		const transactionBytes = this.getBasicBytes();
		if (
			this._networkIdentifier === undefined ||
			this._networkIdentifier === ''
		) {
			throw new Error(
				'Network identifier is required to validate a transaction ',
			);
		}
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
 
		this._id = getId(this.getBytes());
 
		const {
			valid: signatureValid,
			error: verificationError,
		} = validateSignature(
			this.senderPublicKey,
			this.signature,
			transactionWithNetworkIdentifierBytes,
			this.id,
		);
 
		if (!signatureValid && verificationError) {
			errors.push(verificationError);
		}
 
		if (this.type !== (this.constructor as typeof BaseTransaction).TYPE) {
			errors.push(
				new TransactionError(
					`Invalid type`,
					this.id,
					'.type',
					this.type,
					(this.constructor as typeof BaseTransaction).TYPE,
				),
			);
		}
 
		return createResponse(this.id, errors);
	}
 
	// tslint:disable-next-line prefer-function-over-method
	protected verifyAgainstTransactions(
		_: ReadonlyArray<TransactionJSON>,
	): ReadonlyArray<TransactionError> {
		return [];
	}
 
	public verifyAgainstOtherTransactions(
		transactions: ReadonlyArray<TransactionJSON>,
	): TransactionResponse {
		const errors = this.verifyAgainstTransactions(transactions);
 
		return createResponse(this.id, errors);
	}
 
	public async apply(store: StateStore): Promise<TransactionResponse> {
		const sender = await store.account.getOrDefault(this.senderId);
		const errors = this._verify(sender) as TransactionError[];
 
		// Verify MultiSignature
		const { errors: multiSigError } = await this.processMultisignatures(store);
		Eif (multiSigError) {
			errors.push(...multiSigError);
		}
 
		const updatedBalance = BigInt(sender.balance) - BigInt(this.fee);
		const updatedSender = {
			...sender,
			balance: updatedBalance.toString(),
			publicKey: sender.publicKey || this.senderPublicKey,
		};
		store.account.set(updatedSender.address, updatedSender);
		const assetErrors = await this.applyAsset(store);
 
		errors.push(...assetErrors);
 
		Iif (
			this._multisignatureStatus === MultisignatureStatus.PENDING &&
			errors.length === 1 &&
			errors[0] instanceof TransactionPendingError
		) {
			return {
				id: this.id,
				status: Status.PENDING,
				errors,
			};
		}
 
		return createResponse(this.id, errors);
	}
 
	public async undo(store: StateStore): Promise<TransactionResponse> {
		const sender = await store.account.getOrDefault(this.senderId);
		const updatedBalance = BigInt(sender.balance) + this.fee;
		const updatedAccount = {
			...sender,
			balance: updatedBalance.toString(),
			publicKey: sender.publicKey || this.senderPublicKey,
		};
		const errors =
			updatedBalance <= BigInt(MAX_TRANSACTION_AMOUNT)
				? []
				: [
						new TransactionError(
							'Invalid balance amount',
							this.id,
							'.balance',
							sender.balance,
							updatedBalance.toString(),
						),
				  ];
		store.account.set(updatedAccount.address, updatedAccount);
		const assetErrors = await this.undoAsset(store);
		errors.push(...assetErrors);
 
		return createResponse(this.id, errors);
	}
 
	public async prepare(store: StateStorePrepare): Promise<void> {
		await store.account.cache([
			{
				address: this.senderId,
			},
		]);
	}
 
	public async addMultisignature(
		store: StateStore,
		signatureObject: SignatureObject,
	): Promise<TransactionResponse> {
		// Get the account
		const account = await store.account.get(this.senderId);
		// Validate signature key belongs to account's multisignature group
		if (
			account.membersPublicKeys &&
			!account.membersPublicKeys.includes(signatureObject.publicKey)
		) {
			return createResponse(this.id, [
				new TransactionError(
					`Public Key '${signatureObject.publicKey}' is not a member for account '${account.address}'.`,
					this.id,
				),
			]);
		}
 
		// Check if signature is not already there
		if (this.signatures.includes(signatureObject.signature)) {
			return createResponse(this.id, [
				new TransactionError(
					`Signature '${signatureObject.signature}' already present in transaction.`,
					this.id,
				),
			]);
		}
 
		const transactionBytes = this.getBasicBytes();
		Iif (
			this._networkIdentifier === undefined ||
			this._networkIdentifier === ''
		) {
			throw new Error(
				'Network identifier is required to validate a transaction ',
			);
		}
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
 
		// Validate the signature using the signature sender and transaction details
		const { valid } = validateSignature(
			signatureObject.publicKey,
			signatureObject.signature,
			transactionWithNetworkIdentifierBytes,
			this.id,
		);
		// If the signature is valid for the sender push it to the signatures array
		Eif (valid) {
			this.signatures.push(signatureObject.signature);
 
			return this.processMultisignatures(store);
		}
 
		// Else populate errors
		const errors = [
			new TransactionError(
				`Failed to add signature '${signatureObject.signature}'.`,
				this.id,
				'.signatures',
			),
		];
 
		return createResponse(this.id, errors);
	}
 
	public addVerifiedMultisignature(signature: string): TransactionResponse {
		if (!this.signatures.includes(signature)) {
			this.signatures.push(signature);
 
			return createResponse(this.id, []);
		}
 
		return createResponse(this.id, [
			new TransactionError('Failed to add signature.', this.id, '.signatures'),
		]);
	}
 
	public async processMultisignatures(
		store: StateStore,
	): Promise<TransactionResponse> {
		const sender = await store.account.get(this.senderId);
		const transactionBytes = this.getBasicBytes();
		Iif (
			this._networkIdentifier === undefined ||
			this._networkIdentifier === ''
		) {
			throw new Error(
				'Network identifier is required to validate a transaction ',
			);
		}
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
 
		const { status, errors } = verifyMultiSignatures(
			this.id,
			sender,
			this.signatures,
			transactionWithNetworkIdentifierBytes,
		);
		this._multisignatureStatus = status;
		if (this._multisignatureStatus === MultisignatureStatus.PENDING) {
			return {
				id: this.id,
				status: Status.PENDING,
				errors,
			};
		}
 
		return createResponse(this.id, errors);
	}
 
	public isExpired(date: Date = new Date()): boolean {
		Iif (!this.receivedAt) {
			this.receivedAt = new Date();
		}
		// tslint:disable-next-line no-magic-numbers
		const timeNow = Math.floor(date.getTime() / 1000);
		const timeOut =
			this._multisignatureStatus === MultisignatureStatus.PENDING ||
			this._multisignatureStatus === MultisignatureStatus.READY
				? UNCONFIRMED_MULTISIG_TRANSACTION_TIMEOUT
				: UNCONFIRMED_TRANSACTION_TIMEOUT;
		const timeElapsed =
			// tslint:disable-next-line no-magic-numbers
			timeNow - Math.floor(this.receivedAt.getTime() / 1000);
 
		return timeElapsed > timeOut;
	}
 
	public sign(passphrase: string, secondPassphrase?: string): void {
		const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase);
 
		Iif (this._senderPublicKey !== '' && this._senderPublicKey !== publicKey) {
			throw new Error(
				'Transaction senderPublicKey does not match public key from passphrase',
			);
		}
 
		this._senderPublicKey = publicKey;
 
		this._signature = undefined;
		this._signSignature = undefined;
 
		if (
			this._networkIdentifier === undefined ||
			this._networkIdentifier === ''
		) {
			throw new Error('Network identifier is required to sign a transaction ');
		}
 
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			this.getBytes(),
		]);
 
		this._signature = signData(
			hash(transactionWithNetworkIdentifierBytes),
			passphrase,
		);
 
		if (secondPassphrase) {
			this._signSignature = signData(
				hash(
					Buffer.concat([
						transactionWithNetworkIdentifierBytes,
						hexToBuffer(this._signature),
					]),
				),
				secondPassphrase,
			);
		}
 
		this._id = getId(this.getBytes());
	}
 
	protected getBasicBytes(): Buffer {
		const transactionType = Buffer.alloc(BYTESIZES.TYPE, this.type);
		const transactionTimestamp = Buffer.alloc(BYTESIZES.TIMESTAMP);
		transactionTimestamp.writeIntBE(this.timestamp, 0, BYTESIZES.TIMESTAMP);
		const transactionSenderPublicKey = hexToBuffer(this.senderPublicKey);
 
		return Buffer.concat([
			transactionType,
			transactionTimestamp,
			transactionSenderPublicKey,
			this.assetToBytes(),
		]);
	}
 
	public assetToJSON(): object {
		return this.asset;
	}
 
	protected assetToBytes(): Buffer {
		/**
		 * FixMe: The following method is not sufficient enough for more sophisticated cases,
		 * i.e. properties in the asset object need to be sent always in the same right order to produce a deterministic signature.
		 *
		 * We are currently conducting a research to specify an optimal generic way of changing asset to bytes.
		 * You can expect this enhanced implementation to be included in the next releases.
		 */
 
		return Buffer.from(JSON.stringify(this.asset), 'utf-8');
	}
 
	private _verify(sender: Account): ReadonlyArray<TransactionError> {
		const transactionBytes = this.getBasicBytes();
		Iif (
			this._networkIdentifier === undefined ||
			this._networkIdentifier === ''
		) {
			throw new Error(
				'Network identifier is required to verify a transaction ',
			);
		}
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
		const secondSignatureTxBytes = Buffer.concat([
			transactionWithNetworkIdentifierBytes,
			hexToBuffer(this.signature),
		]);
 
		// Verify Basic state
		return [
			verifySenderPublicKey(this.id, sender, this.senderPublicKey),
			verifyBalance(this.id, sender, this.fee),
			verifySecondSignature(
				this.id,
				sender,
				this.signSignature,
				secondSignatureTxBytes,
			),
		].filter(Boolean) as ReadonlyArray<TransactionError>;
	}
 
	private _validateSchema(): ReadonlyArray<TransactionError> {
		const transaction = this.toJSON();
		const schemaErrors = validator.validate(
			schemas.baseTransaction,
			transaction,
		);
		const errors = convertToTransactionError(
			this.id,
			schemaErrors,
		) as TransactionError[];
 
		if (
			!errors.find(
				(err: TransactionError) => err.dataPath === '.senderPublicKey',
			)
		) {
			// `senderPublicKey` passed format check, safely check equality to senderId
			const senderIdError = validateSenderIdAndPublicKey(
				this.id,
				this.senderId,
				this.senderPublicKey,
			);
			Iif (senderIdError) {
				errors.push(senderIdError);
			}
		}
 
		return errors;
	}
}