From 7fb76ed7191ecad7ad7b100c35196e5424a5b3dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20M=C3=BCller?= Date: Mon, 2 Dec 2024 10:02:00 -0800 Subject: [PATCH] address at index is only valid in range [1 .. 2^45 - 1] --- contracts/LinearCodeAddressGenerator.cdc | 7 +++- tests/LinearCodeAddressGenerator_test.cdc | 39 ++++++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/contracts/LinearCodeAddressGenerator.cdc b/contracts/LinearCodeAddressGenerator.cdc index d868ef06..b9b9003a 100644 --- a/contracts/LinearCodeAddressGenerator.cdc +++ b/contracts/LinearCodeAddressGenerator.cdc @@ -91,7 +91,12 @@ contract LinearCodeAddressGenerator { /// Returns the address at the given index, for the given chain. access(all) - fun address(at index: UInt64, chain: Chain): Address { + fun address(at index: UInt64, chain: Chain): Address? { + // The index must be in the range [1 .. 2^45 - 1] + // TODO: Use Cadence exponentiation operator, once available + if index < 1 || index > 35184372088831 { + return nil + } return Address(self.encodeWord(index) ^ self.invalidCodeWord(forChain: chain)) } diff --git a/tests/LinearCodeAddressGenerator_test.cdc b/tests/LinearCodeAddressGenerator_test.cdc index c1b78373..969e1d05 100644 --- a/tests/LinearCodeAddressGenerator_test.cdc +++ b/tests/LinearCodeAddressGenerator_test.cdc @@ -22,7 +22,7 @@ fun generateAddresses( at: index, chain: chain ) - addresses.append(address) + addresses.append(address!) } return addresses @@ -127,3 +127,40 @@ fun testTransient() { ] ) } + +access(all) +fun testAddressAtIndex() { + + let minIndex: UInt64 = 1 + let maxIndex: UInt64 = 35184372088831 + + for chain in [ + LinearCodeAddressGenerator.Chain.Mainnet, + LinearCodeAddressGenerator.Chain.Testnet, + LinearCodeAddressGenerator.Chain.Transient + ] { + let lessThanMinAddress = LinearCodeAddressGenerator.address( + at: minIndex - 1, + chain: chain + ) + Test.assert(lessThanMinAddress == nil) + + let minAddress = LinearCodeAddressGenerator.address( + at: minIndex, + chain: chain + ) + Test.assert(minAddress != nil) + + let maxAddress = LinearCodeAddressGenerator.address( + at: maxIndex, + chain: chain + ) + Test.assert(maxAddress != nil) + + let greaterThanMaxAddress = LinearCodeAddressGenerator.address( + at: 35184372088832, + chain: chain + ) + Test.assert(greaterThanMaxAddress == nil) + } +} \ No newline at end of file