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
20 changes: 20 additions & 0 deletions packages/sdk/src/__tests__/ContractDeployer.edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,26 @@ describe('ContractDeployer — edge cases', () => {
expect(Buffer.compare(lastSalt1 ?? Buffer.alloc(0), lastSalt2 ?? Buffer.alloc(1))).not.toBe(0);
});

it('generates 32-byte salts with crypto randomness, independent of Math.random', () => {
const mathRandom = vi.spyOn(Math, 'random').mockReturnValue(0.5);

try {
const privateDeployer = deployer as unknown as { randomSalt: () => Buffer };
const salt1 = privateDeployer.randomSalt();
const salt2 = privateDeployer.randomSalt();
const mathRandomSalt = Buffer.alloc(32, 128);

expect(salt1).toHaveLength(32);
expect(salt2).toHaveLength(32);
expect(salt1.equals(mathRandomSalt)).toBe(false);
expect(salt2.equals(mathRandomSalt)).toBe(false);
expect(Buffer.compare(salt1, salt2)).not.toBe(0);
expect(mathRandom).not.toHaveBeenCalled();
} finally {
mathRandom.mockRestore();
}
});

it('different passphrase => hash() called with different passphrase bytes', async () => {
const { hash: mockHash } = await import('@stellar/stellar-sdk');
const salt = Buffer.alloc(32, 0x55);
Expand Down
5 changes: 2 additions & 3 deletions packages/sdk/src/deployer/ContractDeployer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { randomBytes } from 'node:crypto';
import {
Keypair,
TransactionBuilder,
Expand Down Expand Up @@ -552,9 +553,7 @@ export class ContractDeployer {
}

private randomSalt(): Buffer {
const buf = Buffer.alloc(32);
for (let i = 0; i < 32; i++) buf[i] = Math.floor(Math.random() * 256);
return buf;
return randomBytes(32);
}
}

Expand Down