From ada493f607f3e55603e266f5d7d50b4a354b7259 Mon Sep 17 00:00:00 2001 From: Justin Starry Date: Mon, 29 Aug 2022 22:20:16 +0200 Subject: [PATCH] feat: add VersionedMessage.deserializeMessageVersion utility function (#27415) --- web3.js/src/message/versioned.ts | 15 ++++++++--- web3.js/test/message-tests/versioned.test.ts | 28 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 web3.js/test/message-tests/versioned.test.ts diff --git a/web3.js/src/message/versioned.ts b/web3.js/src/message/versioned.ts index 042fc1c72fcebb..92b4d888bdbf67 100644 --- a/web3.js/src/message/versioned.ts +++ b/web3.js/src/message/versioned.ts @@ -5,17 +5,26 @@ import {MessageV0} from './v0'; export type VersionedMessage = Message | MessageV0; // eslint-disable-next-line no-redeclare export const VersionedMessage = { - deserialize: (serializedMessage: Uint8Array): VersionedMessage => { + deserializeMessageVersion(serializedMessage: Uint8Array): 'legacy' | number { const prefix = serializedMessage[0]; const maskedPrefix = prefix & VERSION_PREFIX_MASK; // if the highest bit of the prefix is not set, the message is not versioned if (maskedPrefix === prefix) { - return Message.from(serializedMessage); + return 'legacy'; } // the lower 7 bits of the prefix indicate the message version - const version = maskedPrefix; + return maskedPrefix; + }, + + deserialize: (serializedMessage: Uint8Array): VersionedMessage => { + const version = + VersionedMessage.deserializeMessageVersion(serializedMessage); + if (version === 'legacy') { + return Message.from(serializedMessage); + } + if (version === 0) { return MessageV0.deserialize(serializedMessage); } else { diff --git a/web3.js/test/message-tests/versioned.test.ts b/web3.js/test/message-tests/versioned.test.ts new file mode 100644 index 00000000000000..1acaf7823b1443 --- /dev/null +++ b/web3.js/test/message-tests/versioned.test.ts @@ -0,0 +1,28 @@ +import {expect} from 'chai'; + +import {VersionedMessage} from '../../src/message'; + +describe('VersionedMessage', () => { + it('deserializeMessageVersion', () => { + const bufferWithLegacyPrefix = new Uint8Array([1]); + expect( + VersionedMessage.deserializeMessageVersion(bufferWithLegacyPrefix), + ).to.eq('legacy'); + + for (const version of [0, 1, 127]) { + const bufferWithVersionPrefix = new Uint8Array([(1 << 7) + version]); + expect( + VersionedMessage.deserializeMessageVersion(bufferWithVersionPrefix), + ).to.eq(version); + } + }); + + it('deserialize failure', () => { + const bufferWithV1Prefix = new Uint8Array([(1 << 7) + 1]); + expect(() => { + VersionedMessage.deserialize(bufferWithV1Prefix); + }).to.throw( + 'Transaction message version 1 deserialization is not supported', + ); + }); +});