2021-09-14 11:36:55 +00:00
|
|
|
# Nimbus - Portal Network
|
|
|
|
# Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
{.used.}
|
|
|
|
|
|
|
|
import
|
2021-09-21 12:35:41 +00:00
|
|
|
std/sequtils,
|
|
|
|
stint, unittest2,
|
2021-10-09 11:22:03 +00:00
|
|
|
../network/state/state_distance
|
2021-09-14 11:36:55 +00:00
|
|
|
|
|
|
|
suite "State network custom distance function":
|
|
|
|
test "Calculate distance according to spec":
|
|
|
|
check:
|
|
|
|
# Test cases from spec
|
2021-10-09 11:22:03 +00:00
|
|
|
stateDistance(u256(10), u256(10)) == 0
|
|
|
|
stateDistance(u256(5), high(UInt256)) == 6
|
|
|
|
stateDistance(high(UInt256), u256(6)) == 7
|
|
|
|
stateDistance(u256(5), u256(1)) == 4
|
|
|
|
stateDistance(u256(1), u256(5)) == 4
|
|
|
|
stateDistance(UInt256.zero, MID) == MID
|
|
|
|
stateDistance(UInt256.zero, MID + UInt256.one) == MID - UInt256.one
|
2021-09-14 11:36:55 +00:00
|
|
|
|
|
|
|
# Additional test cases to check some basic properties
|
2021-10-09 11:22:03 +00:00
|
|
|
stateDistance(UInt256.zero, MID + MID) == UInt256.zero
|
|
|
|
stateDistance(UInt256.zero, UInt256.one) == stateDistance(UInt256.zero, high(UInt256))
|
2021-09-16 14:13:36 +00:00
|
|
|
|
|
|
|
test "Calculate logarithimic distance":
|
|
|
|
check:
|
2021-10-09 11:22:03 +00:00
|
|
|
stateLogDistance(u256(0), u256(0)) == 0
|
|
|
|
stateLogDistance(u256(0), u256(1)) == 0
|
|
|
|
stateLogDistance(u256(0), u256(2)) == 1
|
|
|
|
stateLogDistance(u256(0), u256(4)) == 2
|
|
|
|
stateLogDistance(u256(0), u256(8)) == 3
|
|
|
|
stateLogDistance(u256(8), u256(0)) == 3
|
|
|
|
stateLogDistance(UInt256.zero, MID) == 255
|
|
|
|
stateLogDistance(UInt256.zero, MID + UInt256.one) == 254
|
2021-09-16 14:13:36 +00:00
|
|
|
|
|
|
|
test "Calculate id at log distance":
|
|
|
|
let logDistances = @[
|
|
|
|
0'u16, 1, 2, 3, 4, 5, 6, 7, 8
|
|
|
|
]
|
|
|
|
|
|
|
|
# for each log distance, calulate node-id at given distance from node zero, and then
|
|
|
|
# log distance from calculate node-id to node zero. The results should equal
|
|
|
|
# starting log distances
|
|
|
|
let logCalculated = logDistances.map(
|
|
|
|
proc (x: uint16): uint16 =
|
2021-10-09 11:22:03 +00:00
|
|
|
let nodeAtDist = stateIdAtDistance(Uint256.zero, x)
|
|
|
|
return stateLogDistance(Uint256.zero, nodeAtDist)
|
2021-09-16 14:13:36 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
check:
|
|
|
|
logDistances == logCalculated
|