Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make makeNonce return unique random values #546

Merged
merged 6 commits into from Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
}