Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,11 @@ export class PermissionlessValidatorTxBuilder extends TransactionBuilder {
utxos.push(new Utxo(utxoId, assetId, transferInputs));

inputs.push(input);
if (!this.transaction.credentials || this.transaction.credentials.length == 0) {
// Only populate fresh placeholder credentials the first time this tx is built.
// Must be a null check, not a length check: an already-established credentials=[]
// is a bug state (see Transaction.hasCredentials) and must surface via the sign()/
// toBroadcastFormat() guards, not be silently regenerated over here.
if (this.transaction.credentials == null) {
if (buildOutputs) {
// For the bitgo signature we create an empty signature
// For the user/backup signature we store the address that matches the key
Expand Down
70 changes: 65 additions & 5 deletions modules/sdk-coin-avaxp/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,24 @@ function isEmptySignature(signature: string): boolean {
return !!signature && utils.removeHexPrefix(signature).startsWith(''.padStart(90, '0'));
}

/**
* An address placeholder is 90 zero hex chars (45-byte prefix) followed by a 20-byte address.
* A purely empty slot is all zeros. Non-zero bytes after position 90 distinguish the two.
* A real ECDSA alongside an addr placeholder in the same credential set means one signer's
* pass never replaced the placeholder -- signing is incomplete and must not be broadcast.
* @see CECHO-1697, CSHLD-1550
*/
function isAddrPlaceholder(signature: string): boolean {
if (!isEmptySignature(signature)) {
return false;
}
const stripped = utils.removeHexPrefix(signature);
const suffix = stripped.substring(90);
return suffix.length > 0 && suffix !== ''.padStart(suffix.length, '0');
}

interface CheckSignature {
(sigature: string, addressHex: string): boolean;
(signature: string, addressHex: string): boolean;
}

function generateSelectorSignature(signatures: string[]): CheckSignature {
Expand Down Expand Up @@ -86,18 +102,38 @@ export class Transaction extends BaseTransaction {
}

get signature(): string[] {
if (this.credentials.length === 0) {
if (!this.credentials || this.credentials.length === 0) {
return [];
}
return this.credentials[0].getSignatures().filter((s) => !isEmptySignature(s));
// Use the intersection of non-empty signatures across all credentials. A signer's
// ECDSA is counted only if it appears in every credential (every input), so a
// credential that is still missing a signature another credential already has
// does not surface a false-complete signature set.
let intersection: Set<string> | null = null;
for (const c of this.credentials) {
const credSigs = new Set<string>(c.getSignatures().filter((s) => !isEmptySignature(s)));
if (intersection === null) {
intersection = credSigs;
} else {
for (const sig of intersection) {
if (!credSigs.has(sig)) {
intersection.delete(sig);
}
}
}
}
return intersection ? [...intersection] : [];
}

get credentials(): Credential[] {
return (this._avaxTransaction as UnsignedTx)?.credentials;
}

get hasCredentials(): boolean {
return this.credentials !== undefined && this.credentials.length > 0;
// Guard against credential regeneration whenever credentials have been set from a parsed
// tx. Must use != null (not a length check) so credentials=[] is still recognized as an
// established (if buggy) state rather than "never built".
return this.credentials != null;
}

/** @inheritdoc */
Expand All @@ -119,7 +155,7 @@ export class Transaction extends BaseTransaction {
if (!this.avaxPTransaction) {
throw new InvalidTransactionError('empty transaction to sign');
}
if (!this.hasCredentials) {
if (!this.credentials || this.credentials.length === 0) {
throw new InvalidTransactionError('empty credentials to sign');
}
const unsignedTx = this._avaxTransaction as UnsignedTx;
Expand Down Expand Up @@ -161,6 +197,30 @@ export class Transaction extends BaseTransaction {
if (!this.avaxPTransaction) {
throw new InvalidTransactionError('Empty transaction data');
}
// credentials=[] is always a bug: hasCredentials treats it as "established" so a rebuild
// won't silently regenerate placeholders over it, but an empty array means no signer has
// actually touched the tx -- serializing it would produce a zero-credential tx.
if (this.credentials != null && this.credentials.length === 0) {
throw new InvalidTransactionError('transaction has no credentials — cannot broadcast');
}
Comment thread
Copilot marked this conversation as resolved.
if (this.credentials && this.credentials.length > 0) {
let hasRealSig = false;
let hasAddrPlaceholder = false;
for (const c of this.credentials) {
for (const s of c.getSignatures()) {
if (!isEmptySignature(s)) {
hasRealSig = true;
} else if (isAddrPlaceholder(s)) {
hasAddrPlaceholder = true;
}
}
}
if (hasRealSig && hasAddrPlaceholder) {
throw new InvalidTransactionError(
'transaction has a real ECDSA alongside an address placeholder (r=0): incomplete signing detected, refusing broadcast'
);
}
}
return this.toHexString(avaxUtils.addChecksum((this._avaxTransaction as UnsignedTx).getSignedTx().toBytes()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,132 @@ describe('AvaxP permissionlessValidatorTxBuilder', () => {
console.log(fullSignedTx.toJson());
});
});
describe('Credential guard bypass regression (CSHLD-1550)', () => {
// PR #9287 (CECHO-1697) hardened deprecatedTransaction.ts against credential corruption
// but explicitly (and incorrectly) marked PermissionlessValidatorTxBuilder as "not
// affected". CSHLD-1550 is an AddPermissionlessValidatorTx broadcast rejected on-chain
// with "invalid signature" -- this suite confirms transaction.ts now carries the same
// guards that were added to deprecatedTransaction.ts.
const buildHalfSigned = async (): Promise<string> => {
const unixNow = BigInt(Math.round(new Date().getTime() / 1000));
const startTime = unixNow + BigInt(60);
const endTime = startTime + BigInt(60 * 60 * 24 + 600);
const txBuilder = new AvaxpLib.TransactionBuilderFactory(coins.get('tavaxp'))
.getPermissionlessValidatorTxBuilder()
.threshold(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.threshold)
.locktime(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.locktime)
.recoverMode(false)
.fromPubKey(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.bitgoAddresses)
.startTime(startTime.toString())
.endTime(endTime.toString())
.stakeAmount(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.stakeAmount)
.delegationFeeRate(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.delegationFeeRate)
.nodeID(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.nodeId)
.blsPublicKey(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.blsPublicKey)
.blsSignature(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.blsSignature)
.utxos(testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.utxos);
await txBuilder.build();
txBuilder.sign({ key: testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.userPrivateKey });
const halfSigned = await txBuilder.build();
return halfSigned.toBroadcastFormat();
};

it('hasCredentials returns true for credentials=[] preventing silent credential regeneration', async () => {
const halfSignedHex = await buildHalfSigned();
const signer2Builder = factory.from(halfSignedHex) as any;
const internalTx = signer2Builder.transaction;
// Simulate the bug trigger: credentials=[] on the parsed tx
internalTx._avaxTransaction.credentials = [];
internalTx.hasCredentials.should.be.true(
'hasCredentials must return true for credentials=[] to block credential regeneration in calculateUtxos()'
);
});

it('toBroadcastFormat() throws when credentials=[] rather than serializing a zero-credential tx', async () => {
const halfSignedHex = await buildHalfSigned();
const builder = factory.from(halfSignedHex) as any;
const tx = (await builder.build()) as any;
// Force credentials=[] directly on a built tx, bypassing sign() entirely, to exercise
// the toBroadcastFormat() guard in isolation.
tx._avaxTransaction.credentials = [];
assert.throws(
() => tx.toBroadcastFormat(),
(e: any) => e.message === 'transaction has no credentials — cannot broadcast'
);
});

it('sign() throws on empty credentials rather than silently producing a bad tx', async () => {
const halfSignedHex = await buildHalfSigned();
const signer2Builder = factory.from(halfSignedHex) as any;
signer2Builder.sign({ key: testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.backupPrivateKey });
signer2Builder.transaction._avaxTransaction.credentials = [];
await signer2Builder
.build()
.then(() => assert.fail('Expected sign to throw on empty credentials'))
.catch((e: any) => {
e.message.should.equal('empty credentials to sign');
});
});

it('signature getter exposes incomplete signing across all credentials via intersection', async () => {
const halfSignedHex = await buildHalfSigned();
const halfBuilder = factory.from(halfSignedHex) as any;
const halfTx = await halfBuilder.build();
halfTx.signature.length.should.equal(
1,
'should expose exactly 1 real ECDSA after first signer -- second signer slot is still empty'
);

const fullBuilder = factory.from(halfSignedHex) as any;
fullBuilder.sign({ key: testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.backupPrivateKey });
const fullTx = await fullBuilder.build();
fullTx.signature.length.should.equal(2, 'sanity: fully signed tx should have 2 signatures');

// Corrupt one slot of one credential back to an empty (zeroed) signature. A union of
// per-credential signatures would still report 2 (masking the corruption); the
// intersection must drop to however many signatures remain common to every credential.
const creds = (fullTx as any).credentials;
assert.ok(creds && creds.length > 0, 'fully signed tx must have credentials');
const zeroSig = Buffer.from(''.padStart(130, '0'), 'hex');
creds[0].setSignature(0, zeroSig);

fullTx.signature.length.should.be.lessThan(
2,
'intersection must detect that credentials[0] is missing a signature -- incomplete signing visible'
);
});

it('toBroadcastFormat() throws when a real ECDSA coexists with an address placeholder', async () => {
const halfSignedHex = await buildHalfSigned();
const fullBuilder = factory.from(halfSignedHex) as any;
fullBuilder.sign({ key: testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.backupPrivateKey });
const fullTx = (await fullBuilder.build()) as any;

const creds = fullTx.credentials;
assert.ok(creds && creds.length > 0, 'fully signed tx must have credentials');
// 90 zero hex chars (45-byte prefix) + 20-byte address -- the exact placeholder shape
// produced by calculateUtxos() for an unfilled signer slot.
const addrPlaceholder = Buffer.from(''.padStart(90, '0') + 'df32717bd7b7a2d50a715202795940250c7ba9e4', 'hex');
creds[0].setSignature(0, addrPlaceholder);

assert.throws(
() => fullTx.toBroadcastFormat(),
(e: any) =>
e.message ===
'transaction has a real ECDSA alongside an address placeholder (r=0): incomplete signing detected, refusing broadcast'
);
});

it('full sign from half-signed hex still produces a valid fully-signed tx', async () => {
const halfSignedHex = await buildHalfSigned();
const fullBuilder = factory.from(halfSignedHex);
fullBuilder.sign({ key: testData.BUILD_AND_SIGN_ADD_PERMISSIONLESS_VALIDATOR_SAMPLE.backupPrivateKey });
const fullTx = await fullBuilder.build();
fullTx.signature.length.should.equal(2, 'both signer slots must be filled with real ECDSAs');
assert.doesNotThrow(() => fullTx.toBroadcastFormat());
});
});

it('Should fail to build if utxos change output 0', async () => {
const unixNow = BigInt(Math.round(new Date().getTime() / 1000));
const startTime = unixNow + BigInt(60);
Expand Down
Loading