Skip to content

Commit

Permalink
fix: make makeNonce return unique random values (#546)
Browse files Browse the repository at this point in the history
[SDK-396]
* fix: make makeNonce return unique random values

* fix: makeNonce generates 128 bits of data in the nonce, not 8

view.setBigUInt(1,...) sets data starting at byte offset 1, not byte offset 9 (where the second bigint would start)

* Fixes https://dfinity.atlassian.net/browse/SDK-396
  • Loading branch information
ericswanson-dfinity committed Mar 25, 2022
1 parent 9b663c6 commit 1717113
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
7 changes: 7 additions & 0 deletions docs/generated/changelog.html
Expand Up @@ -10,6 +10,13 @@
<h1>Agent-JS Changelog</h1>

<section>
<h2>Version 0.10.5</h2>
<ul>
<li>
makeNonce now returns unique values. Previously only the first byte of the nonce was
populated.
</li>
</ul>
<h2>Version 0.10.3</h2>
<ul>
<li>
Expand Down
10 changes: 9 additions & 1 deletion packages/agent/src/agent/http/http.test.ts
@@ -1,13 +1,14 @@
import { HttpAgent, Nonce } from '../index';
import * as cbor from '../../cbor';
import { Expiry, makeNonceTransform } from './transforms';
import { CallRequest, Envelope, SubmitRequestType } from './types';
import { CallRequest, Envelope, makeNonce, SubmitRequestType } from './types';
import { Principal } from '@dfinity/principal';
import { requestIdOf } from '../../request_id';

import { JSDOM } from 'jsdom';
import { AnonymousIdentity, SignIdentity } from '../..';
import { Ed25519KeyIdentity } from '../../../../identity/src/identity/ed25519';
import { toHexString } from '../../../../identity/src/buffer';
import { AgentError } from '../../errors';
const { window } = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
window.fetch = global.fetch;
Expand Down Expand Up @@ -354,3 +355,10 @@ describe('replace identity', () => {
expect(mockFetch).toBeCalledTimes(1);
});
});
describe('makeNonce should create unique values', () => {
const nonces = new Set();
for (let i = 0; i < 100; i++) {
nonces.add(toHexString(makeNonce()));
}
expect(nonces.size).toBe(100);
});
10 changes: 6 additions & 4 deletions packages/agent/src/agent/http/types.ts
Expand Up @@ -107,10 +107,12 @@ export function makeNonce(): Nonce {
// Encode 128 bits.
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);
const value = BigInt(+Date.now()) * BigInt(100000) + BigInt(Math.floor(Math.random() * 100000));
view.setBigUint64(0, value);
// tslint:disable-next-line:no-bitwise
view.setBigUint64(1, value >> BigInt(64));
const now = BigInt(+Date.now());
const randHi = Math.floor(Math.random() * 0xffffffff);
const randLo = Math.floor(Math.random() * 0xffffffff);
view.setBigUint64(0, now);
view.setUint32(8, randHi);
view.setUint32(12, randLo);

return buffer as Nonce;
}

0 comments on commit 1717113

Please sign in to comment.