All files / src 12_multisignature_transaction.ts

95.35% Statements 82/86
81.08% Branches 30/37
100% Functions 17/17
95.24% Lines 80/84

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                            5x       5x   5x           5x   5x         5x   5x   5x                                                     5x       4x 12x 12x 12x       12x       5x 15x               5x   5x 5x 63x       63x 63x     63x   63x                 45x 45x 45x 45x   45x       1x   3x   1x                     2x     2x       1x             2x       5x       5x         5x 4x     1x                     1x           7x 7x 7x         7x 21x               7x 1x   1x     6x         5x   5x             1x   1x           4x 4x     4x 2x                   4x                   4x           4x   4x   4x           2x   2x             2x   2x               21x   7x 3x                 4x 1x               3x 3x 3x           3x             3x 3x   3x                              
/*
 * 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 {
	getAddressFromPublicKey,
	hexToBuffer,
} from '@liskhq/lisk-cryptography';
import { validator } from '@liskhq/lisk-validator';
 
import {
	BaseTransaction,
	MultisignatureStatus,
	StateStore,
	StateStorePrepare,
} from './base_transaction';
import { MULTISIGNATURE_FEE } from './constants';
import { SignatureObject } from './create_signature_object';
import {
	convertToAssetError,
	TransactionError,
	TransactionPendingError,
} from './errors';
import { createResponse, Status, TransactionResponse } from './response';
import { TransactionJSON } from './transaction_types';
import { validateMultisignatures, validateSignature } from './utils';
 
export const multisignatureAssetFormatSchema = {
	type: 'object',
	required: ['min', 'lifetime', 'keysgroup'],
	properties: {
		min: {
			type: 'integer',
			minimum: 1,
			maximum: 15,
		},
		lifetime: {
			type: 'integer',
			minimum: 1,
			maximum: 72,
		},
		keysgroup: {
			type: 'array',
			uniqueItems: true,
			minItems: 1,
			maxItems: 15,
			items: {
				type: 'string',
				format: 'additionPublicKey',
			},
		},
	},
};
 
const setMemberAccounts = async (
	store: StateStore,
	membersPublicKeys: ReadonlyArray<string>,
) => {
	for (const memberPublicKey of membersPublicKeys) {
		const address = getAddressFromPublicKey(memberPublicKey);
		const memberAccount = await store.account.getOrDefault(address);
		const memberAccountWithPublicKey = {
			...memberAccount,
			publicKey: memberAccount.publicKey || memberPublicKey,
		};
		store.account.set(memberAccount.address, memberAccountWithPublicKey);
	}
};
 
const extractPublicKeysFromAsset = (assetPublicKeys: ReadonlyArray<string>) =>
	assetPublicKeys.map(key => key.substring(1));
 
export interface MultiSignatureAsset {
	readonly keysgroup: ReadonlyArray<string>;
	readonly lifetime: number;
	readonly min: number;
}
 
export class MultisignatureTransaction extends BaseTransaction {
	public readonly asset: MultiSignatureAsset;
	public static TYPE = 12;
	public static FEE = MULTISIGNATURE_FEE.toString();
	protected _multisignatureStatus: MultisignatureStatus =
		MultisignatureStatus.PENDING;
 
	public constructor(rawTransaction: unknown) {
		super(rawTransaction);
		const tx = (typeof rawTransaction === 'object' && rawTransaction !== null
			? rawTransaction
			: {}) as Partial<TransactionJSON>;
		this.asset = (tx.asset || {}) as MultiSignatureAsset;
		// Overwrite fee as it is different from the static fee
		this.fee =
			BigInt(MultisignatureTransaction.FEE) *
			((this.asset.keysgroup && this.asset.keysgroup.length
				? BigInt(this.asset.keysgroup.length)
				: BigInt(0)) +
				BigInt(1));
	}
 
	protected assetToBytes(): Buffer {
		const { min, lifetime, keysgroup } = this.asset;
		const minBuffer = Buffer.alloc(1, min);
		const lifetimeBuffer = Buffer.alloc(1, lifetime);
		const keysgroupBuffer = Buffer.from(keysgroup.join(''), 'utf8');
 
		return Buffer.concat([minBuffer, lifetimeBuffer, keysgroupBuffer]);
	}
 
	public async prepare(store: StateStorePrepare): Promise<void> {
		const membersAddresses = extractPublicKeysFromAsset(
			this.asset.keysgroup,
		).map(publicKey => ({ address: getAddressFromPublicKey(publicKey) }));
 
		await store.account.cache([
			{
				address: this.senderId,
			},
			...membersAddresses,
		]);
	}
 
	protected verifyAgainstTransactions(
		transactions: ReadonlyArray<TransactionJSON>,
	): ReadonlyArray<TransactionError> {
		const errors = transactions
			.filter(
				tx =>
					tx.type === this.type && tx.senderPublicKey === this.senderPublicKey,
			)
			.map(
				tx =>
					new TransactionError(
						'Register multisignature only allowed once per account.',
						tx.id,
						'.asset.multisignature',
					),
			);
 
		return errors;
	}
 
	protected validateAsset(): ReadonlyArray<TransactionError> {
		const schemaErrors = validator.validate(
			multisignatureAssetFormatSchema,
			this.asset,
		);
		const errors = convertToAssetError(
			this.id,
			schemaErrors,
		) as TransactionError[];
 
		if (errors.length > 0) {
			return errors;
		}
 
		Iif (this.asset.min > this.asset.keysgroup.length) {
			errors.push(
				new TransactionError(
					'Invalid multisignature min. Must be less than or equal to keysgroup size',
					this.id,
					'.asset.min',
					this.asset.min,
				),
			);
		}
 
		return errors;
	}
 
	public async processMultisignatures(
		_: StateStore,
	): Promise<TransactionResponse> {
		const transactionBytes = this.getBasicBytes();
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
 
		const { valid, errors } = validateMultisignatures(
			this.asset.keysgroup.map(signedPublicKey => signedPublicKey.substring(1)),
			this.signatures,
			// Required to get signature from all of keysgroup
			this.asset.keysgroup.length,
			transactionWithNetworkIdentifierBytes,
			this.id,
		);
 
		if (valid) {
			this._multisignatureStatus = MultisignatureStatus.READY;
 
			return createResponse(this.id, errors);
		}
 
		if (
			errors &&
			errors.length === 1 &&
			errors[0] instanceof TransactionPendingError
		) {
			this._multisignatureStatus = MultisignatureStatus.PENDING;
 
			return {
				id: this.id,
				status: Status.PENDING,
				errors,
			};
		}
 
		this._multisignatureStatus = MultisignatureStatus.FAIL;
 
		return createResponse(this.id, errors);
	}
 
	protected async applyAsset(
		store: StateStore,
	): Promise<ReadonlyArray<TransactionError>> {
		const errors: TransactionError[] = [];
		const sender = await store.account.get(this.senderId);
 
		// Check if multisignatures already exists on account
		if (sender.membersPublicKeys && sender.membersPublicKeys.length > 0) {
			errors.push(
				new TransactionError(
					'Register multisignature only allowed once per account.',
					this.id,
					'.signatures',
				),
			);
		}
 
		// Check if multisignatures includes sender's own publicKey
		Iif (this.asset.keysgroup.includes(`+${sender.publicKey}`)) {
			errors.push(
				new TransactionError(
					'Invalid multisignature keysgroup. Can not contain sender',
					this.id,
					'.signatures',
				),
			);
		}
 
		const updatedSender = {
			...sender,
			membersPublicKeys: extractPublicKeysFromAsset(this.asset.keysgroup),
			multiMin: this.asset.min,
			multiLifetime: this.asset.lifetime,
		};
		store.account.set(updatedSender.address, updatedSender);
 
		await setMemberAccounts(store, updatedSender.membersPublicKeys);
 
		return errors;
	}
 
	protected async undoAsset(
		store: StateStore,
	): Promise<ReadonlyArray<TransactionError>> {
		const sender = await store.account.get(this.senderId);
 
		const resetSender = {
			...sender,
			membersPublicKeys: [],
			multiMin: 0,
			multiLifetime: 0,
		};
 
		store.account.set(resetSender.address, resetSender);
 
		return [];
	}
 
	public async addMultisignature(
		store: StateStore,
		signatureObject: SignatureObject,
	): Promise<TransactionResponse> {
		// Validate signature key belongs to pending multisig registration transaction
		const keysgroup = this.asset.keysgroup.map((aKey: string) => aKey.slice(1));
 
		if (!keysgroup.includes(signatureObject.publicKey)) {
			return createResponse(this.id, [
				new TransactionError(
					`Public Key '${signatureObject.publicKey}' is not a member.`,
					this.id,
				),
			]);
		}
 
		// Check if signature is already present
		if (this.signatures.includes(signatureObject.signature)) {
			return createResponse(this.id, [
				new TransactionError(
					'Encountered duplicate signature in transaction',
					this.id,
				),
			]);
		}
 
		const transactionBytes = this.getBasicBytes();
		const networkIdentifierBytes = hexToBuffer(this._networkIdentifier);
		const transactionWithNetworkIdentifierBytes = Buffer.concat([
			networkIdentifierBytes,
			transactionBytes,
		]);
 
		// Check if signature is valid at all
		const { valid } = validateSignature(
			signatureObject.publicKey,
			signatureObject.signature,
			transactionWithNetworkIdentifierBytes,
			this.id,
		);
 
		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);
	}
}