Skip to content

Commit

Permalink
address at index is only valid in range [1 .. 2^45 - 1]
Browse files Browse the repository at this point in the history
  • Loading branch information
turbolent committed Dec 2, 2024
1 parent aecc974 commit 7fb76ed
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
7 changes: 6 additions & 1 deletion contracts/LinearCodeAddressGenerator.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}

Expand Down
39 changes: 38 additions & 1 deletion tests/LinearCodeAddressGenerator_test.cdc
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fun generateAddresses(
at: index,
chain: chain
)
addresses.append(address)
addresses.append(address!)
}

return addresses
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 7fb76ed

Please sign in to comment.