From eca2e545256e68512d961117160aede09a7b1608 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 24 Jan 2020 11:52:46 -0300 Subject: [PATCH 01/70] uint256: add first implementation for Int256 --- uint256/int256.go | 146 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 uint256/int256.go diff --git a/uint256/int256.go b/uint256/int256.go new file mode 100644 index 0000000000..a202fa20ae --- /dev/null +++ b/uint256/int256.go @@ -0,0 +1,146 @@ +// Copyright 2020 The Swarm Authors +// This file is part of the Swarm library. +// +// The Swarm library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Swarm library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the Swarm library. If not, see . + +package uint256 + +import ( + "fmt" + "io" + "math/big" + + "github.com/ethereum/go-ethereum/rlp" +) + +// Int256 represents an signed integer of 256 bits +type Int256 struct { + value big.Int +} + +var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) +var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)) // 2^255 - 1 + +// New creates a Int256 struct with a minimum initial underlying value +func (u *Int256) New() *Int256 { + u = new(Int256) + u.value = *new(big.Int).Set(minInt256) + return u +} + +// FromUint64 creates a Int256 struct based on the given uint64 param +// any uint64 is valid as a Int256 +func (u *Int256) FromUint64(base uint64) *Int256 { + u = u.New() + u.value = *new(big.Int).SetUint64(base) + return u +} + +// Value returns the underlying private value for a Int256 struct +func (u *Int256) Value() big.Int { + return u.value +} + +// Set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct +// returns an error when the result falls outside of the unsigned 256-bit integer range +func (u *Int256) Set(value big.Int) (*Int256, error) { + if value.Cmp(maxInt256) == 1 { + return nil, fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) + } + if value.Cmp(minInt256) == -1 { + return nil, fmt.Errorf("cannot set Int256 to %v as it underflows min value of %v", value, minInt256) + } + u.value = *new(big.Int).Set(&value) + return u, nil +} + +// Copy sets the underlying value of u to a copy of the given Int256 param, and returns the modified receiver struct +func (u *Int256) Copy(v *Int256) *Int256 { + u.value = *new(big.Int).Set(&v.value) + return u +} + +// Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field +func (u *Int256) Cmp(v *Int256) int { + return u.value.Cmp(&v.value) +} + +// Equals returns true if the two Int256 structs have the same underlying values, false otherwise +func (u *Int256) Equals(v *Int256) bool { + return u.Cmp(v) == 0 +} + +// Add sets u to augend + addend and returns u as the sum +// returns an error when the result falls outside of the signed 256-bit integer range +func (u *Int256) Add(augend, addend *Int256) (*Int256, error) { + sum := new(big.Int).Add(&augend.value, &addend.value) + return u.Set(*sum) +} + +// Sub sets u to minuend - subtrahend and returns u as the difference +// returns an error when the result falls outside of the signed 256-bit integer range +func (u *Int256) Sub(minuend, subtrahend *Int256) (*Int256, error) { + difference := new(big.Int).Sub(&minuend.value, &subtrahend.value) + return u.Set(*difference) +} + +// Mul sets u to multiplicand * multiplier and returns u as the product +// returns an error when the result falls outside of the signed 256-bit integer range +func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { + product := new(big.Int).Mul(&multiplicand.value, &multiplier.value) + return u.Set(*product) +} + +// String returns the string representation for Int256 structs +func (u *Int256) String() string { + return u.value.String() +} + +// MarshalJSON implements the json.Marshaler interface +// it specifies how to marshal a Int256 struct so that it can be written to disk +func (u Int256) MarshalJSON() ([]byte, error) { + return []byte(u.value.String()), nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface +// it specifies how to unmarshal a Int256 struct so that it can be reconstructed from disk +func (u *Int256) UnmarshalJSON(b []byte) error { + if string(b) == "null" { + return nil + } + + var value big.Int + _, ok := value.SetString(string(b), 10) + if !ok { + return fmt.Errorf("not a valid integer value: %s", b) + } + _, err := u.Set(value) + return err +} + +// EncodeRLP implements the rlp.Encoder interface +// it makes sure the `value` field is encoded even though it is private +func (u *Int256) EncodeRLP(w io.Writer) error { + return rlp.Encode(w, &u.value) +} + +// DecodeRLP implements the rlp.Decoder interface +// it makes sure the `value` field is decoded even though it is private +func (u *Int256) DecodeRLP(s *rlp.Stream) error { + if err := s.Decode(&u.value); err != nil { + return nil + } + _, err := u.Set(u.value) + return err +} From 08df85bf741bd06c954ed83b6472320e78a96941 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 24 Jan 2020 12:19:51 -0300 Subject: [PATCH 02/70] uint256: iterate implementation for Int256, refactor Uint256 --- swap/api.go | 2 +- swap/cashout_test.go | 2 +- swap/cheque.go | 2 +- swap/peer.go | 4 ++-- swap/swap.go | 2 +- swap/swap_test.go | 2 +- uint256/int256.go | 7 +++---- uint256/uint256.go | 6 +++--- uint256/uint256_test.go | 6 +++--- 9 files changed, 16 insertions(+), 17 deletions(-) diff --git a/swap/api.go b/swap/api.go index dc29f2c1a9..59ac32361c 100644 --- a/swap/api.go +++ b/swap/api.go @@ -91,7 +91,7 @@ func (s *Swap) AvailableBalance() (*uint256.Uint256, error) { totalChequesWorth := new(big.Int).Sub(cashedChequesWorth, sentChequesWorth) tentativeLiquidBalance := new(big.Int).Add(contractLiquidBalance, totalChequesWorth) - return uint256.New().Set(*tentativeLiquidBalance) + return uint256.NewUint256().Set(*tentativeLiquidBalance) } // PeerBalance returns the balance for a given peer diff --git a/swap/cashout_test.go b/swap/cashout_test.go index 54b62b11e5..31c2f3ea35 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -74,7 +74,7 @@ func TestContractIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - paidOut, err := uint256.New().Set(*result) + paidOut, err := uint256.NewUint256().Set(*result) if err != nil { t.Fatal(err) } diff --git a/swap/cheque.go b/swap/cheque.go index 5b27a435d9..80df983531 100644 --- a/swap/cheque.go +++ b/swap/cheque.go @@ -134,7 +134,7 @@ func (cheque *Cheque) verifyChequeProperties(p *Peer, expectedBeneficiary common // verifyChequeAgainstLast verifies that the amount is higher than in the previous cheque and the increase is as expected // returns the actual amount received in this cheque func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *uint256.Uint256) (*uint256.Uint256, error) { - actualAmount := uint256.New().Copy(cheque.CumulativePayout) + actualAmount := uint256.NewUint256().Copy(cheque.CumulativePayout) if lastCheque != nil { if cheque.CumulativePayout.Cmp(lastCheque.CumulativePayout) < 1 { diff --git a/swap/peer.go b/swap/peer.go index 174d71c953..364561576c 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -122,7 +122,7 @@ func (p *Peer) getLastSentCumulativePayout() *uint256.Uint256 { if lastCheque != nil { return lastCheque.CumulativePayout } - return uint256.New() + return uint256.NewUint256() } // the caller is expected to hold p.lock @@ -170,7 +170,7 @@ func (p *Peer) createCheque() (*Cheque, error) { price := uint256.FromUint64(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() - newCumulativePayout, err := uint256.New().Add(cumulativePayout, price) + newCumulativePayout, err := uint256.NewUint256().Add(cumulativePayout, price) if err != nil { return nil, err } diff --git a/swap/swap.go b/swap/swap.go index c92149b1a0..efe2cc72a5 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -441,7 +441,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque payout := uint256.FromUint64(expectedPayout) costs := uint256.FromUint64(transactionCosts) costsMultiplier := uint256.FromUint64(2) - costThreshold, err := uint256.New().Mul(costs, costsMultiplier) + costThreshold, err := uint256.NewUint256().Mul(costs, costsMultiplier) if err != nil { return err } diff --git a/swap/swap_test.go b/swap/swap_test.go index bc00b98558..f1e1d8e9e3 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -1061,7 +1061,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := uint256.New().Add(increase, uint256.FromUint64(5)) + cumulativePayoutIncrease, err := uint256.NewUint256().Add(increase, uint256.FromUint64(5)) if err != nil { t.Fatal(err) } diff --git a/uint256/int256.go b/uint256/int256.go index a202fa20ae..4e29ab7c17 100644 --- a/uint256/int256.go +++ b/uint256/int256.go @@ -32,9 +32,9 @@ type Int256 struct { var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)) // 2^255 - 1 -// New creates a Int256 struct with a minimum initial underlying value -func (u *Int256) New() *Int256 { - u = new(Int256) +// NewInt256 creates a Int256 struct with a minimum initial underlying value +func NewInt256() *Int256 { + u := new(Int256) u.value = *new(big.Int).Set(minInt256) return u } @@ -42,7 +42,6 @@ func (u *Int256) New() *Int256 { // FromUint64 creates a Int256 struct based on the given uint64 param // any uint64 is valid as a Int256 func (u *Int256) FromUint64(base uint64) *Int256 { - u = u.New() u.value = *new(big.Int).SetUint64(base) return u } diff --git a/uint256/uint256.go b/uint256/uint256.go index 173a5d4a58..bd29a9ceb8 100644 --- a/uint256/uint256.go +++ b/uint256/uint256.go @@ -32,8 +32,8 @@ type Uint256 struct { var minUint256 = big.NewInt(0) var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)) // 2^256 - 1 -// New creates a Uint256 struct with a minimum initial underlying value -func New() *Uint256 { +// NewUint256 creates a Uint256 struct with a minimum initial underlying value +func NewUint256() *Uint256 { u := new(Uint256) u.value = *new(big.Int).Set(minUint256) return u @@ -42,7 +42,7 @@ func New() *Uint256 { // FromUint64 creates a Uint256 struct based on the given uint64 param // any uint64 is valid as a Uint256 func FromUint64(base uint64) *Uint256 { - u := New() + u := NewUint256() u.value = *new(big.Int).SetUint64(base) return u } diff --git a/uint256/uint256_test.go b/uint256/uint256_test.go index 8c1fbe913e..76dfa2bf3b 100644 --- a/uint256/uint256_test.go +++ b/uint256/uint256_test.go @@ -96,7 +96,7 @@ func testSet(t *testing.T, testCases []Uint256TestCase) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result, err := New().Set(*tc.baseInteger) + result, err := NewUint256().Set(*tc.baseInteger) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Uint256, but got none") } @@ -120,7 +120,7 @@ func TestCopy(t *testing.T) { t.Fatal(err) } - c := New().Copy(r) + c := NewUint256().Copy(r) if !c.Equals(r) { t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) @@ -135,7 +135,7 @@ func randomUint256() (*Uint256, error) { randomUint256 := new(big.Int).Add(r, minUint256) // random is within [minUint256, maxUint256] - return New().Set(*randomUint256) + return NewUint256().Set(*randomUint256) } // TestStore indirectly tests the marshaling and unmarshaling of a random Uint256 variable From c6e096056c3cc7157e2cd826545f0b8f38345d88 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 24 Jan 2020 15:03:45 -0300 Subject: [PATCH 03/70] uint256: rename package to boundedint --- {uint256 => boundedint}/int256.go | 2 +- {uint256 => boundedint}/uint256.go | 2 +- {uint256 => boundedint}/uint256_test.go | 2 +- swap/api.go | 8 ++++---- swap/cashout_test.go | 4 ++-- swap/cheque.go | 6 +++--- swap/common_test.go | 8 ++++---- swap/peer.go | 10 +++++----- swap/protocol_test.go | 6 +++--- swap/simulations_test.go | 10 +++++----- swap/swap.go | 14 +++++++------- swap/swap_test.go | 22 +++++++++++----------- swap/types.go | 4 ++-- 13 files changed, 49 insertions(+), 49 deletions(-) rename {uint256 => boundedint}/int256.go (99%) rename {uint256 => boundedint}/uint256.go (99%) rename {uint256 => boundedint}/uint256_test.go (99%) diff --git a/uint256/int256.go b/boundedint/int256.go similarity index 99% rename from uint256/int256.go rename to boundedint/int256.go index 4e29ab7c17..12565c3187 100644 --- a/uint256/int256.go +++ b/boundedint/int256.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package uint256 +package boundedint import ( "fmt" diff --git a/uint256/uint256.go b/boundedint/uint256.go similarity index 99% rename from uint256/uint256.go rename to boundedint/uint256.go index bd29a9ceb8..62e721e767 100644 --- a/uint256/uint256.go +++ b/boundedint/uint256.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package uint256 +package boundedint import ( "fmt" diff --git a/uint256/uint256_test.go b/boundedint/uint256_test.go similarity index 99% rename from uint256/uint256_test.go rename to boundedint/uint256_test.go index 76dfa2bf3b..60e5adc5fc 100644 --- a/uint256/uint256_test.go +++ b/boundedint/uint256_test.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package uint256 +package boundedint import ( "crypto/rand" diff --git a/swap/api.go b/swap/api.go index 59ac32361c..ecfe95b690 100644 --- a/swap/api.go +++ b/swap/api.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // APIs is a node.Service interface method @@ -25,7 +25,7 @@ func (s *Swap) APIs() []rpc.API { } type swapAPI interface { - AvailableBalance() (*uint256.Uint256, error) + AvailableBalance() (*boundedint.Uint256, error) PeerBalance(peer enode.ID) (int64, error) Balances() (map[enode.ID]int64, error) PeerCheques(peer enode.ID) (PeerCheques, error) @@ -54,7 +54,7 @@ func NewAPI(s *Swap) *API { } // AvailableBalance returns the total balance of the chequebook against which new cheques can be written -func (s *Swap) AvailableBalance() (*uint256.Uint256, error) { +func (s *Swap) AvailableBalance() (*boundedint.Uint256, error) { // get the LiquidBalance of the chequebook contractLiquidBalance, err := s.contract.LiquidBalance(nil) if err != nil { @@ -91,7 +91,7 @@ func (s *Swap) AvailableBalance() (*uint256.Uint256, error) { totalChequesWorth := new(big.Int).Sub(cashedChequesWorth, sentChequesWorth) tentativeLiquidBalance := new(big.Int).Add(contractLiquidBalance, totalChequesWorth) - return uint256.NewUint256().Set(*tentativeLiquidBalance) + return boundedint.NewUint256().Set(*tentativeLiquidBalance) } // PeerBalance returns the balance for a given peer diff --git a/swap/cashout_test.go b/swap/cashout_test.go index 31c2f3ea35..07bc060579 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -24,7 +24,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/log" contract "github.com/ethersphere/swarm/contracts/swap" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // TestContractIntegration tests a end-to-end cheque interaction. @@ -74,7 +74,7 @@ func TestContractIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - paidOut, err := uint256.NewUint256().Set(*result) + paidOut, err := boundedint.NewUint256().Set(*result) if err != nil { t.Fatal(err) } diff --git a/swap/cheque.go b/swap/cheque.go index 80df983531..857b195c3d 100644 --- a/swap/cheque.go +++ b/swap/cheque.go @@ -23,7 +23,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // encodeForSignature encodes the cheque params in the format used in the signing procedure @@ -133,8 +133,8 @@ func (cheque *Cheque) verifyChequeProperties(p *Peer, expectedBeneficiary common // verifyChequeAgainstLast verifies that the amount is higher than in the previous cheque and the increase is as expected // returns the actual amount received in this cheque -func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *uint256.Uint256) (*uint256.Uint256, error) { - actualAmount := uint256.NewUint256().Copy(cheque.CumulativePayout) +func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *boundedint.Uint256) (*boundedint.Uint256, error) { + actualAmount := boundedint.NewUint256().Copy(cheque.CumulativePayout) if lastCheque != nil { if cheque.CumulativePayout.Cmp(lastCheque.CumulativePayout) < 1 { diff --git a/swap/common_test.go b/swap/common_test.go index e4c673a605..a25fe02e0c 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -24,7 +24,7 @@ import ( "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // swapTestBackend encapsulates the SimulatedBackend and can offer @@ -168,7 +168,7 @@ func newTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: uint256.FromUint64(42), + CumulativePayout: boundedint.FromUint64(42), Beneficiary: beneficiaryAddress, }, Honey: uint64(42), @@ -181,7 +181,7 @@ func newSignedTestCheque(testChequeContract common.Address, beneficiaryAddress c cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: uint256.FromUint64(cumulativePayout.Uint64()), + CumulativePayout: boundedint.FromUint64(cumulativePayout.Uint64()), Beneficiary: beneficiaryAddress, }, Honey: cumulativePayout.Uint64(), @@ -202,7 +202,7 @@ func newRandomTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: uint256.FromUint64(amount), + CumulativePayout: boundedint.FromUint64(amount), Beneficiary: beneficiaryAddress, }, Honey: amount, diff --git a/swap/peer.go b/swap/peer.go index 364561576c..39b595635b 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -27,7 +27,7 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" "github.com/ethersphere/swarm/p2p/protocols" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // ErrDontOwe indictates that no balance is actially owned @@ -117,12 +117,12 @@ func (p *Peer) setPendingCheque(cheque *Cheque) error { // getLastSentCumulativePayout returns the cumulative payout of the last sent cheque or 0 if there is none // the caller is expected to hold p.lock -func (p *Peer) getLastSentCumulativePayout() *uint256.Uint256 { +func (p *Peer) getLastSentCumulativePayout() *boundedint.Uint256 { lastCheque := p.getLastSentCheque() if lastCheque != nil { return lastCheque.CumulativePayout } - return uint256.NewUint256() + return boundedint.NewUint256() } // the caller is expected to hold p.lock @@ -167,10 +167,10 @@ func (p *Peer) createCheque() (*Cheque, error) { if err != nil { return nil, fmt.Errorf("error getting price from oracle: %v", err) } - price := uint256.FromUint64(oraclePrice) + price := boundedint.FromUint64(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() - newCumulativePayout, err := uint256.NewUint256().Add(cumulativePayout, price) + newCumulativePayout, err := boundedint.NewUint256().Add(cumulativePayout, price) if err != nil { return nil, err } diff --git a/swap/protocol_test.go b/swap/protocol_test.go index cc5c85eddb..5ca3dae11a 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -35,7 +35,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" contract "github.com/ethersphere/swarm/contracts/swap" p2ptest "github.com/ethersphere/swarm/p2p/testing" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" colorable "github.com/mattn/go-colorable" ) @@ -246,7 +246,7 @@ func TestEmitCheque(t *testing.T) { // gasPrice on testBackend == 1 // estimated gas costs == 50000 // cheque should be sent if the accumulated amount of uncashed cheques is worth more than 100000 - balance := uint256.FromUint64(100001) + balance := boundedint.FromUint64(100001) balanceValue := balance.Value() if err := testDeploy(context.Background(), debitorSwap, &balanceValue); err != nil { @@ -382,7 +382,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal("Expected pending cheque") } - if !pending.CumulativePayout.Equals(uint256.FromUint64(expectedAmount)) { + if !pending.CumulativePayout.Equals(boundedint.FromUint64(expectedAmount)) { t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index 53cbd863da..6e4d6abcf5 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -47,7 +47,7 @@ import ( "github.com/ethersphere/swarm/network/simulation" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) /* @@ -369,10 +369,10 @@ func TestPingPongChequeSimulation(t *testing.T) { } expected := uint64(maxCheques) / 2 * (DefaultPaymentThreshold + 1) - if !ch1.CumulativePayout.Equals(uint256.FromUint64(expected)) { + if !ch1.CumulativePayout.Equals(boundedint.FromUint64(expected)) { t.Fatalf("expected cumulative payout to be %d, but is %v", expected, ch1.CumulativePayout) } - if !ch2.CumulativePayout.Equals(uint256.FromUint64(expected)) { + if !ch2.CumulativePayout.Equals(boundedint.FromUint64(expected)) { t.Fatalf("expected cumulative payout to be %d, but is %v", expected, ch2.CumulativePayout) } @@ -510,7 +510,7 @@ func TestMultiChequeSimulation(t *testing.T) { // check also the actual expected amount expectedPayout = uint64(maxCheques) * (DefaultPaymentThreshold + 1) - if !cheque2.CumulativePayout.Equals(uint256.FromUint64(expectedPayout)) { + if !cheque2.CumulativePayout.Equals(boundedint.FromUint64(expectedPayout)) { t.Fatalf("Expected %d in cumulative payout, got %v", expectedPayout, cheque1.CumulativePayout) } @@ -746,7 +746,7 @@ func waitForChequeProcessed(t *testing.T, backend *swapTestBackend, counter metr p.lock.Lock() lastPayout := p.getLastSentCumulativePayout() p.lock.Unlock() - if !lastPayout.Equals(uint256.FromUint64(expectedLastPayout)) { + if !lastPayout.Equals(boundedint.FromUint64(expectedLastPayout)) { time.Sleep(5 * time.Millisecond) continue } else { diff --git a/swap/swap.go b/swap/swap.go index efe2cc72a5..4214232dfe 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -39,7 +39,7 @@ import ( "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // ErrInvalidChequeSignature indicates the signature on the cheque was invalid @@ -438,10 +438,10 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque return protocols.Break(err) } - payout := uint256.FromUint64(expectedPayout) - costs := uint256.FromUint64(transactionCosts) - costsMultiplier := uint256.FromUint64(2) - costThreshold, err := uint256.NewUint256().Mul(costs, costsMultiplier) + payout := boundedint.FromUint64(expectedPayout) + costs := boundedint.FromUint64(transactionCosts) + costsMultiplier := boundedint.FromUint64(2) + costThreshold, err := boundedint.NewUint256().Mul(costs, costsMultiplier) if err != nil { return err } @@ -496,7 +496,7 @@ func cashCheque(s *Swap, cheque *Cheque) { // processAndVerifyCheque verifies the cheque and compares it with the last received cheque // if the cheque is valid it will also be saved as the new last cheque -func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*uint256.Uint256, error) { +func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*boundedint.Uint256, error) { if err := cheque.verifyChequeProperties(p, s.owner.address); err != nil { return nil, err } @@ -509,7 +509,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*uint256.Uint256 return nil, err } - actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, uint256.FromUint64(expectedAmount)) + actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, boundedint.FromUint64(expectedAmount)) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index f1e1d8e9e3..3b3be34d7e 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -48,7 +48,7 @@ import ( "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" "github.com/ethersphere/swarm/testutil" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) var ( @@ -586,7 +586,7 @@ func TestPaymentThreshold(t *testing.T) { var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(uint256.FromUint64(DefaultPaymentThreshold)) { + if !cheque.CumulativePayout.Equals(boundedint.FromUint64(DefaultPaymentThreshold)) { t.Fatal() } } @@ -1027,7 +1027,7 @@ func TestPeerVerifyChequePropertiesInvalidCheque(t *testing.T) { // TestPeerVerifyChequeAgainstLast tests that verifyChequeAgainstLast accepts a cheque with higher amount func TestPeerVerifyChequeAgainstLast(t *testing.T) { - increase := uint256.FromUint64(10) + increase := boundedint.FromUint64(10) oldCheque := newTestCheque() newCheque := newTestCheque() @@ -1048,7 +1048,7 @@ func TestPeerVerifyChequeAgainstLast(t *testing.T) { // TestPeerVerifyChequeAgainstLastInvalid tests that verifyChequeAgainstLast rejects cheques with lower amount or an unexpected value func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { - increase := uint256.FromUint64(10) + increase := boundedint.FromUint64(10) // cheque with same or lower amount oldCheque := newTestCheque() @@ -1061,7 +1061,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := uint256.NewUint256().Add(increase, uint256.FromUint64(5)) + cumulativePayoutIncrease, err := boundedint.NewUint256().Add(increase, boundedint.FromUint64(5)) if err != nil { t.Fatal(err) } @@ -1101,7 +1101,7 @@ func TestPeerProcessAndVerifyCheque(t *testing.T) { // create another cheque with higher amount otherCheque := newTestCheque() - _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, uint256.FromUint64(10)) + _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, boundedint.FromUint64(10)) if err != nil { t.Fatal(err) } @@ -1149,7 +1149,7 @@ func TestPeerProcessAndVerifyChequeInvalid(t *testing.T) { // invalid cheque because amount is lower otherCheque := newTestCheque() - _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, uint256.FromUint64(10)) + _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, boundedint.FromUint64(10)) if err != nil { t.Fatal(err) } @@ -1260,7 +1260,7 @@ func TestPeerGetLastSentCumulativePayout(t *testing.T) { _, peer, clean := newTestSwapAndPeer(t, ownerKey) defer clean() - if !peer.getLastSentCumulativePayout().Equals(uint256.FromUint64(0)) { + if !peer.getLastSentCumulativePayout().Equals(boundedint.FromUint64(0)) { t.Fatalf("last cumulative payout should be 0 in the beginning, was %v", peer.getLastSentCumulativePayout()) } @@ -1300,7 +1300,7 @@ func TestAvailableBalance(t *testing.T) { if err != nil { t.Fatal(err) } - if !availableBalance.Equals(uint256.FromUint64(depositAmount.Uint64())) { + if !availableBalance.Equals(boundedint.FromUint64(depositAmount.Uint64())) { t.Fatalf("availableBalance not equal to deposited amount. availableBalance: %v, depositAmount: %d", availableBalance, depositAmount) } // withdraw 50 @@ -1321,7 +1321,7 @@ func TestAvailableBalance(t *testing.T) { if err != nil { t.Fatal(err) } - if !availableBalance.Equals(uint256.FromUint64(netDeposit)) { + if !availableBalance.Equals(boundedint.FromUint64(netDeposit)) { t.Fatalf("availableBalance not equal to deposited minus withdraw. availableBalance: %v, deposit minus withdrawn: %d", availableBalance, depositAmount.Uint64()-withdrawAmount.Uint64()) } @@ -1339,7 +1339,7 @@ func TestAvailableBalance(t *testing.T) { } // verify available balance expectedBalance := netDeposit - uint64(chequeAmount) - if !availableBalance.Equals(uint256.FromUint64(expectedBalance)) { + if !availableBalance.Equals(boundedint.FromUint64(expectedBalance)) { t.Fatalf("availableBalance not equal to deposited minus withdraw. availableBalance: %v, deposit minus withdrawn: %d", availableBalance, depositAmount.Uint64()-withdrawAmount.Uint64()) } diff --git a/swap/types.go b/swap/types.go index 3bf9a3fd4f..5201b92a2b 100644 --- a/swap/types.go +++ b/swap/types.go @@ -18,14 +18,14 @@ package swap import ( "github.com/ethereum/go-ethereum/common" - "github.com/ethersphere/swarm/uint256" + "github.com/ethersphere/swarm/boundedint" ) // ChequeParams encapsulate all cheque parameters type ChequeParams struct { Contract common.Address // address of chequebook, needed to avoid cross-contract submission Beneficiary common.Address // address of the beneficiary, the contract which will redeem the cheque - CumulativePayout *uint256.Uint256 // cumulative amount of the cheque in currency + CumulativePayout *boundedint.Uint256 // cumulative amount of the cheque in currency } // Cheque encapsulates the parameters and the signature From ece8ceb100a9a19d4b510be39a0a884bdba93988 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 27 Jan 2020 15:39:14 -0300 Subject: [PATCH 04/70] swap: fix formatting --- swap/api.go | 2 +- swap/cashout.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/swap/api.go b/swap/api.go index ecfe95b690..5d354dc376 100644 --- a/swap/api.go +++ b/swap/api.go @@ -7,9 +7,9 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" + "github.com/ethersphere/swarm/boundedint" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/boundedint" ) // APIs is a node.Service interface method diff --git a/swap/cashout.go b/swap/cashout.go index 83cb8753cf..cc7c1d0e31 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -22,8 +22,8 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/metrics" - contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/boundedint" + contract "github.com/ethersphere/swarm/contracts/swapint" ) // CashChequeBeneficiaryTransactionCost is the expected gas cost of a CashChequeBeneficiary transaction From 3ab3cdaaddca7c4bd8dc7c262fa96c47f8640d24 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 27 Jan 2020 15:41:49 -0300 Subject: [PATCH 05/70] swap: fix formatting --- swap/cashout.go | 2 +- swap/cashout_test.go | 2 +- swap/common_test.go | 2 +- swap/peer.go | 2 +- swap/protocol_test.go | 2 +- swap/simulations_test.go | 2 +- swap/swap.go | 2 +- swap/swap_test.go | 2 +- swap/types.go | 4 ++-- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/swap/cashout.go b/swap/cashout.go index cc7c1d0e31..3471554f62 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -23,7 +23,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/metrics" "github.com/ethersphere/swarm/boundedint" - contract "github.com/ethersphere/swarm/contracts/swapint" + contract "github.com/ethersphere/swarm/contracts/swap" ) // CashChequeBeneficiaryTransactionCost is the expected gas cost of a CashChequeBeneficiary transaction diff --git a/swap/cashout_test.go b/swap/cashout_test.go index c8ee50a209..b1628820d9 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -22,8 +22,8 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/log" - contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/boundedint" + contract "github.com/ethersphere/swarm/contracts/swap" ) // TestContractIntegration tests a end-to-end cheque interaction. diff --git a/swap/common_test.go b/swap/common_test.go index ed675666bb..3b0fcdc105 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -20,11 +20,11 @@ import ( "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/simulations/adapters" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" + "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/boundedint" ) // swapTestBackend encapsulates the SimulatedBackend and can offer diff --git a/swap/peer.go b/swap/peer.go index 39b595635b..c223227204 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -26,8 +26,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" - "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/boundedint" + "github.com/ethersphere/swarm/p2p/protocols" ) // ErrDontOwe indictates that no balance is actially owned diff --git a/swap/protocol_test.go b/swap/protocol_test.go index dfff4d20c1..12881347b7 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -32,9 +32,9 @@ import ( "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" + "github.com/ethersphere/swarm/boundedint" contract "github.com/ethersphere/swarm/contracts/swap" p2ptest "github.com/ethersphere/swarm/p2p/testing" - "github.com/ethersphere/swarm/boundedint" colorable "github.com/mattn/go-colorable" ) diff --git a/swap/simulations_test.go b/swap/simulations_test.go index 894d2203ff..f933a49d82 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -43,11 +43,11 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/rpc" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" + "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network/simulation" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/boundedint" ) /* diff --git a/swap/swap.go b/swap/swap.go index ecd70a63bc..f4d327c24c 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -34,12 +34,12 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/p2p/enode" + "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/contracts/swap" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" - "github.com/ethersphere/swarm/boundedint" ) // ErrInvalidChequeSignature indicates the signature on the cheque was invalid diff --git a/swap/swap_test.go b/swap/swap_test.go index 19cef15ba6..f3048064db 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -44,11 +44,11 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" + "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" "github.com/ethersphere/swarm/testutil" - "github.com/ethersphere/swarm/boundedint" ) var ( diff --git a/swap/types.go b/swap/types.go index 5201b92a2b..37dc82feaa 100644 --- a/swap/types.go +++ b/swap/types.go @@ -23,8 +23,8 @@ import ( // ChequeParams encapsulate all cheque parameters type ChequeParams struct { - Contract common.Address // address of chequebook, needed to avoid cross-contract submission - Beneficiary common.Address // address of the beneficiary, the contract which will redeem the cheque + Contract common.Address // address of chequebook, needed to avoid cross-contract submission + Beneficiary common.Address // address of the beneficiary, the contract which will redeem the cheque CumulativePayout *boundedint.Uint256 // cumulative amount of the cheque in currency } From 6e8bbcb315e083d63e1c73e3a6996de478548d59 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 27 Jan 2020 16:27:00 -0300 Subject: [PATCH 06/70] swap: rename FromUint64 func to Uint64ToUint256 --- boundedint/int256.go | 7 ------- swap/cashout.go | 2 +- swap/cashout_test.go | 10 +++++----- swap/common_test.go | 4 ++-- swap/peer.go | 2 +- swap/protocol_test.go | 16 ++++++++-------- swap/simulations_test.go | 10 +++++----- swap/swap.go | 4 ++-- swap/swap_test.go | 40 ++++++++++++++++++++-------------------- 9 files changed, 44 insertions(+), 51 deletions(-) diff --git a/boundedint/int256.go b/boundedint/int256.go index 12565c3187..bc645ad131 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -39,13 +39,6 @@ func NewInt256() *Int256 { return u } -// FromUint64 creates a Int256 struct based on the given uint64 param -// any uint64 is valid as a Int256 -func (u *Int256) FromUint64(base uint64) *Int256 { - u.value = *new(big.Int).SetUint64(base) - return u -} - // Value returns the underlying private value for a Int256 struct func (u *Int256) Value() big.Int { return u.value diff --git a/swap/cashout.go b/swap/cashout.go index 3471554f62..a542556c36 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -106,7 +106,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - transactionCosts, err = boundedint.NewUint256().Mul(gasPrice, boundedint.FromUint64(CashChequeBeneficiaryTransactionCost)) + transactionCosts, err = boundedint.NewUint256().Mul(gasPrice, boundedint.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) if err != nil { return nil, nil, err } diff --git a/swap/cashout_test.go b/swap/cashout_test.go index b1628820d9..6440222690 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -36,7 +36,7 @@ func TestContractIntegration(t *testing.T) { reset := setupContractTest() defer reset() - payout := boundedint.FromUint64(42) + payout := boundedint.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -84,7 +84,7 @@ func TestContractIntegration(t *testing.T) { log.Debug("cheques result", "result", result) // create a cheque that will bounce - _, err = payout.Add(payout, boundedint.FromUint64(10000*RetrieveRequestPrice)) + _, err = payout.Add(payout, boundedint.Uint64ToUint256(10000*RetrieveRequestPrice)) if err != nil { t.Fatal(err) } @@ -121,7 +121,7 @@ func TestCashCheque(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := boundedint.FromUint64(42) + payout := boundedint.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -159,7 +159,7 @@ func TestEstimatePayout(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := boundedint.FromUint64(42) + payout := boundedint.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -181,7 +181,7 @@ func TestEstimatePayout(t *testing.T) { } // the gas price in the simulated backend is 1 therefore the total transactionCost should be 50000 * 1 = 50000 - if !transactionCost.Equals(boundedint.FromUint64(CashChequeBeneficiaryTransactionCost)) { + if !transactionCost.Equals(boundedint.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) { t.Fatalf("unexpected transaction cost: got %v, wanted: %d", transactionCost, 0) } } diff --git a/swap/common_test.go b/swap/common_test.go index 3b0fcdc105..63e805d910 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -168,7 +168,7 @@ func newTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: boundedint.FromUint64(42), + CumulativePayout: boundedint.Uint64ToUint256(42), Beneficiary: beneficiaryAddress, }, Honey: uint64(42), @@ -203,7 +203,7 @@ func newRandomTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: boundedint.FromUint64(amount), + CumulativePayout: boundedint.Uint64ToUint256(amount), Beneficiary: beneficiaryAddress, }, Honey: amount, diff --git a/swap/peer.go b/swap/peer.go index c223227204..8bf8e8e071 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -167,7 +167,7 @@ func (p *Peer) createCheque() (*Cheque, error) { if err != nil { return nil, fmt.Errorf("error getting price from oracle: %v", err) } - price := boundedint.FromUint64(oraclePrice) + price := boundedint.Uint64ToUint256(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() newCumulativePayout, err := boundedint.NewUint256().Add(cumulativePayout, price) diff --git a/swap/protocol_test.go b/swap/protocol_test.go index 12881347b7..b451b4c36d 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -135,7 +135,7 @@ func correctSwapHandshakeMsg(swap *Swap) *HandshakeMsg { // TestHandshake tests the correct handshake scenario func TestHandshake(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.FromUint64(0)) + protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -153,7 +153,7 @@ func TestHandshake(t *testing.T) { // TestHandshakeInvalidChainID tests that a handshake with the wrong chain id is rejected func TestHandshakeInvalidChainID(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.FromUint64(0)) + protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -175,7 +175,7 @@ func TestHandshakeInvalidChainID(t *testing.T) { // TestHandshakeEmptyContract tests that a handshake with an empty contract address is rejected func TestHandshakeEmptyContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.FromUint64(0)) + protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -197,7 +197,7 @@ func TestHandshakeEmptyContract(t *testing.T) { // TestHandshakeInvalidContract tests that a handshake with an address that's not a valid chequebook func TestHandshakeInvalidContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.FromUint64(0)) + protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -223,7 +223,7 @@ func TestHandshakeInvalidContract(t *testing.T) { func TestEmitCheque(t *testing.T) { testBackend := newTestBackend(t) - protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.FromUint64(0)) + protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -245,7 +245,7 @@ func TestEmitCheque(t *testing.T) { // gasPrice on testBackend == 1 // estimated gas costs == 50000 // cheque should be sent if the accumulated amount of uncashed cheques is worth more than 100000 - balance := boundedint.FromUint64(100001) + balance := boundedint.Uint64ToUint256(100001) balanceValue := balance.Value() if err := testDeploy(context.Background(), debitorSwap, balance); err != nil { @@ -333,7 +333,7 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.FromUint64(DefaultPaymentThreshold*2)) + protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.Uint64ToUint256(DefaultPaymentThreshold*2)) defer clean() if err != nil { t.Fatal(err) @@ -381,7 +381,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal("Expected pending cheque") } - if !pending.CumulativePayout.Equals(boundedint.FromUint64(expectedAmount)) { + if !pending.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedAmount)) { t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index f933a49d82..cbc9eba174 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -160,7 +160,7 @@ func newSimServiceMap(params *swapSimulationParams) map[string]simulation.Servic ts.spec.Hook = protocols.NewAccounting(balance) ts.swap = balance // deploy the accounting to the `SimulatedBackend` - err = testDeploy(context.Background(), balance, boundedint.FromUint64(100000*RetrieveRequestPrice)) + err = testDeploy(context.Background(), balance, boundedint.Uint64ToUint256(100000*RetrieveRequestPrice)) if err != nil { return nil, nil, err } @@ -369,10 +369,10 @@ func TestPingPongChequeSimulation(t *testing.T) { } expected := uint64(maxCheques) / 2 * (DefaultPaymentThreshold + 1) - if !ch1.CumulativePayout.Equals(boundedint.FromUint64(expected)) { + if !ch1.CumulativePayout.Equals(boundedint.Uint64ToUint256(expected)) { t.Fatalf("expected cumulative payout to be %d, but is %v", expected, ch1.CumulativePayout) } - if !ch2.CumulativePayout.Equals(boundedint.FromUint64(expected)) { + if !ch2.CumulativePayout.Equals(boundedint.Uint64ToUint256(expected)) { t.Fatalf("expected cumulative payout to be %d, but is %v", expected, ch2.CumulativePayout) } @@ -510,7 +510,7 @@ func TestMultiChequeSimulation(t *testing.T) { // check also the actual expected amount expectedPayout = uint64(maxCheques) * (DefaultPaymentThreshold + 1) - if !cheque2.CumulativePayout.Equals(boundedint.FromUint64(expectedPayout)) { + if !cheque2.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedPayout)) { t.Fatalf("Expected %d in cumulative payout, got %v", expectedPayout, cheque1.CumulativePayout) } @@ -746,7 +746,7 @@ func waitForChequeProcessed(t *testing.T, backend *swapTestBackend, counter metr p.lock.Lock() lastPayout := p.getLastSentCumulativePayout() p.lock.Unlock() - if !lastPayout.Equals(boundedint.FromUint64(expectedLastPayout)) { + if !lastPayout.Equals(boundedint.Uint64ToUint256(expectedLastPayout)) { time.Sleep(5 * time.Millisecond) continue } else { diff --git a/swap/swap.go b/swap/swap.go index f4d327c24c..b6bd321804 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -438,7 +438,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque return protocols.Break(err) } - costsMultiplier := boundedint.FromUint64(2) + costsMultiplier := boundedint.Uint64ToUint256(2) costThreshold, err := boundedint.NewUint256().Mul(transactionCosts, costsMultiplier) if err != nil { return err @@ -507,7 +507,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*boundedint.Uint return nil, err } - actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, boundedint.FromUint64(expectedAmount)) + actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, boundedint.Uint64ToUint256(expectedAmount)) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index f3048064db..242b024018 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -434,7 +434,7 @@ func TestStartChequebookFailure(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, config.testBackend) defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.FromUint64(0)) + err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -493,7 +493,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.FromUint64(0)) + err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -519,7 +519,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.FromUint64(0)) + err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -551,7 +551,7 @@ func TestStartChequebookSuccess(t *testing.T) { func TestDisconnectThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, boundedint.FromUint64(0)) + testDeploy(context.Background(), swap, boundedint.Uint64ToUint256(0)) testPeer := newDummyPeer() swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) @@ -577,7 +577,7 @@ func TestDisconnectThreshold(t *testing.T) { func TestPaymentThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, boundedint.FromUint64(DefaultPaymentThreshold)) + testDeploy(context.Background(), swap, boundedint.Uint64ToUint256(DefaultPaymentThreshold)) testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) if err := swap.Add(-int64(DefaultPaymentThreshold), testPeer.Peer); err != nil { @@ -586,7 +586,7 @@ func TestPaymentThreshold(t *testing.T) { var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(boundedint.FromUint64(DefaultPaymentThreshold)) { + if !cheque.CumulativePayout.Equals(boundedint.Uint64ToUint256(DefaultPaymentThreshold)) { t.Fatal() } } @@ -610,11 +610,11 @@ func TestResetBalance(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err := testDeploy(ctx, creditorSwap, boundedint.FromUint64(0)) + err := testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, boundedint.FromUint64(testAmount)) + err = testDeploy(ctx, debitorSwap, boundedint.Uint64ToUint256(testAmount)) if err != nil { t.Fatal(err) } @@ -889,7 +889,7 @@ func TestVerifyContract(t *testing.T) { defer clean() // deploy a new swap contract - err := testDeploy(context.TODO(), swap, boundedint.FromUint64(0)) + err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatalf("Error in deploy: %v", err) } @@ -1027,7 +1027,7 @@ func TestPeerVerifyChequePropertiesInvalidCheque(t *testing.T) { // TestPeerVerifyChequeAgainstLast tests that verifyChequeAgainstLast accepts a cheque with higher amount func TestPeerVerifyChequeAgainstLast(t *testing.T) { - increase := boundedint.FromUint64(10) + increase := boundedint.Uint64ToUint256(10) oldCheque := newTestCheque() newCheque := newTestCheque() @@ -1048,7 +1048,7 @@ func TestPeerVerifyChequeAgainstLast(t *testing.T) { // TestPeerVerifyChequeAgainstLastInvalid tests that verifyChequeAgainstLast rejects cheques with lower amount or an unexpected value func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { - increase := boundedint.FromUint64(10) + increase := boundedint.Uint64ToUint256(10) // cheque with same or lower amount oldCheque := newTestCheque() @@ -1061,7 +1061,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := boundedint.NewUint256().Add(increase, boundedint.FromUint64(5)) + cumulativePayoutIncrease, err := boundedint.NewUint256().Add(increase, boundedint.Uint64ToUint256(5)) if err != nil { t.Fatal(err) } @@ -1101,7 +1101,7 @@ func TestPeerProcessAndVerifyCheque(t *testing.T) { // create another cheque with higher amount otherCheque := newTestCheque() - _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, boundedint.FromUint64(10)) + _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, boundedint.Uint64ToUint256(10)) if err != nil { t.Fatal(err) } @@ -1149,7 +1149,7 @@ func TestPeerProcessAndVerifyChequeInvalid(t *testing.T) { // invalid cheque because amount is lower otherCheque := newTestCheque() - _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, boundedint.FromUint64(10)) + _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, boundedint.Uint64ToUint256(10)) if err != nil { t.Fatal(err) } @@ -1197,11 +1197,11 @@ func TestSwapLogToFile(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err = testDeploy(ctx, creditorSwap, boundedint.FromUint64(testAmount)) + err = testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(testAmount)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, boundedint.FromUint64(0)) + err = testDeploy(ctx, debitorSwap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -1260,7 +1260,7 @@ func TestPeerGetLastSentCumulativePayout(t *testing.T) { _, peer, clean := newTestSwapAndPeer(t, ownerKey) defer clean() - if !peer.getLastSentCumulativePayout().Equals(boundedint.FromUint64(0)) { + if !peer.getLastSentCumulativePayout().Equals(boundedint.Uint64ToUint256(0)) { t.Fatalf("last cumulative payout should be 0 in the beginning, was %v", peer.getLastSentCumulativePayout()) } @@ -1282,7 +1282,7 @@ func TestAvailableBalance(t *testing.T) { cleanup := setupContractTest() defer cleanup() - depositAmount := boundedint.FromUint64(9000 * RetrieveRequestPrice) + depositAmount := boundedint.Uint64ToUint256(9000 * RetrieveRequestPrice) // deploy a chequebook err := testDeploy(context.TODO(), swap, depositAmount) @@ -1304,7 +1304,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatalf("available balance not equal to deposited amount. available balance: %v, deposit amount: %v", availableBalance, depositAmount) } // withdraw 50 - withdrawAmount := boundedint.FromUint64(50) + withdrawAmount := boundedint.Uint64ToUint256(50) netDeposit, err := boundedint.NewUint256().Sub(depositAmount, withdrawAmount) if err != nil { t.Fatal(err) @@ -1343,7 +1343,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatal(err) } // verify available balance - expectedBalance, err := boundedint.NewUint256().Sub(netDeposit, boundedint.FromUint64(chequeAmount)) + expectedBalance, err := boundedint.NewUint256().Sub(netDeposit, boundedint.Uint64ToUint256(chequeAmount)) if err != nil { t.Fatal(err) } From b3013eaa5f0de1c788aca582bfbaf6a7d0c538ba Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 29 Jan 2020 10:41:51 -0300 Subject: [PATCH 07/70] swap: rename FromUint64 to Uint64ToUint256 --- boundedint/uint256.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/boundedint/uint256.go b/boundedint/uint256.go index 62e721e767..87516ffcc8 100644 --- a/boundedint/uint256.go +++ b/boundedint/uint256.go @@ -39,9 +39,9 @@ func NewUint256() *Uint256 { return u } -// FromUint64 creates a Uint256 struct based on the given uint64 param +// Uint64ToUint256 creates a Uint256 struct based on the given uint64 param // any uint64 is valid as a Uint256 -func FromUint64(base uint64) *Uint256 { +func Uint64ToUint256(base uint64) *Uint256 { u := NewUint256() u.value = *new(big.Int).SetUint64(base) return u From 1442c1bd19c804a9c9007587690e91aa66e52260 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 31 Jan 2020 11:57:22 -0300 Subject: [PATCH 08/70] boundedint: small change to comments --- boundedint/int256.go | 4 ++-- boundedint/uint256.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/boundedint/int256.go b/boundedint/int256.go index bc645ad131..1894164ead 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -122,13 +122,13 @@ func (u *Int256) UnmarshalJSON(b []byte) error { } // EncodeRLP implements the rlp.Encoder interface -// it makes sure the `value` field is encoded even though it is private +// it makes sure the value field is encoded even though it is private func (u *Int256) EncodeRLP(w io.Writer) error { return rlp.Encode(w, &u.value) } // DecodeRLP implements the rlp.Decoder interface -// it makes sure the `value` field is decoded even though it is private +// it makes sure the value field is decoded even though it is private func (u *Int256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { return nil diff --git a/boundedint/uint256.go b/boundedint/uint256.go index 87516ffcc8..d5f588bc33 100644 --- a/boundedint/uint256.go +++ b/boundedint/uint256.go @@ -130,13 +130,13 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { } // EncodeRLP implements the rlp.Encoder interface -// it makes sure the `value` field is encoded even though it is private +// it makes sure the value field is encoded even though it is private func (u *Uint256) EncodeRLP(w io.Writer) error { return rlp.Encode(w, &u.value) } // DecodeRLP implements the rlp.Decoder interface -// it makes sure the `value` field is decoded even though it is private +// it makes sure the value field is decoded even though it is private func (u *Uint256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { return nil From 560c13dcdd2d0f2e201c03c114134899a7983214 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 31 Jan 2020 14:54:47 -0300 Subject: [PATCH 09/70] boundedint: add Int64ToInt256 func --- boundedint/int256.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/boundedint/int256.go b/boundedint/int256.go index 1894164ead..5160da9fd0 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -39,6 +39,14 @@ func NewInt256() *Int256 { return u } +// Int64ToInt256 creates a Int256 struct based on the given int64 param +// any int64 is valid as a Int256 +func Int64ToInt256(base int64) *Int256 { + u := NewInt256() + u.value = *new(big.Int).SetInt64(base) + return u +} + // Value returns the underlying private value for a Int256 struct func (u *Int256) Value() big.Int { return u.value From d2ad8f2ef424eeac8ab1daf9b76ebe07386c7ac0 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 3 Feb 2020 17:16:14 -0300 Subject: [PATCH 10/70] boundedint, swarm, swap, main: add BoundedInt interface, change Cmp signature to receive BoundedInt param, change disconnect threshold and payment threshold types to Uint256, change peer balance type to Int256 --- api/config.go | 23 ++++++++--------- boundedint/boundedint.go | 23 +++++++++++++++++ boundedint/int256.go | 7 +++--- boundedint/uint256.go | 7 +++--- cmd/swarm/config.go | 5 ++-- swap/api.go | 12 ++++----- swap/config.go | 9 +++++-- swap/peer.go | 39 ++++++++++++++++------------- swap/swap.go | 53 ++++++++++++++++++++++++++-------------- swarm.go | 4 +-- 10 files changed, 118 insertions(+), 64 deletions(-) create mode 100644 boundedint/boundedint.go diff --git a/api/config.go b/api/config.go index dde0d1494c..fcb2daf437 100644 --- a/api/config.go +++ b/api/config.go @@ -27,6 +27,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p/enode" + "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/contracts/ens" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/pss" @@ -52,15 +53,15 @@ type Config struct { BaseKey []byte // Swap configs - SwapBackendURL string // Ethereum API endpoint - SwapEnabled bool // whether SWAP incentives are enabled - SwapPaymentThreshold uint64 // honey amount at which a payment is triggered - SwapDisconnectThreshold uint64 // honey amount at which a peer disconnects - SwapSkipDeposit bool // do not ask the user to deposit during boot sequence - SwapDepositAmount uint64 // deposit amount to the chequebook - SwapLogPath string // dir to swap related audit logs - Contract common.Address // address of the chequebook contract - SwapChequebookFactory common.Address // address of the chequebook factory contract + SwapBackendURL string // Ethereum API endpoint + SwapEnabled bool // whether SWAP incentives are enabled + SwapPaymentThreshold *boundedint.Uint256 // honey amount at which a payment is triggered + SwapDisconnectThreshold *boundedint.Uint256 // honey amount at which a peer disconnects + SwapSkipDeposit bool // do not ask the user to deposit during boot sequence + SwapDepositAmount uint64 // deposit amount to the chequebook + SwapLogPath string // dir to swap related audit logs + Contract common.Address // address of the chequebook contract + SwapChequebookFactory common.Address // address of the chequebook factory contract // end of Swap configs *network.HiveParams @@ -95,8 +96,8 @@ func NewConfig() *Config { SwapEnabled: false, SwapSkipDeposit: false, SwapDepositAmount: swap.DefaultDepositAmount, - SwapPaymentThreshold: swap.DefaultPaymentThreshold, - SwapDisconnectThreshold: swap.DefaultDisconnectThreshold, + SwapPaymentThreshold: &swap.DefaultPaymentThreshold, + SwapDisconnectThreshold: &swap.DefaultDisconnectThreshold, SwapLogPath: "", HiveParams: network.NewHiveParams(), Pss: pss.NewParams(), diff --git a/boundedint/boundedint.go b/boundedint/boundedint.go new file mode 100644 index 0000000000..08d7d164c1 --- /dev/null +++ b/boundedint/boundedint.go @@ -0,0 +1,23 @@ +// Copyright 2020 The Swarm Authors +// This file is part of the Swarm library. +// +// The Swarm library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Swarm library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the Swarm library. If not, see . + +package boundedint + +import "math/big" + +type BoundedInt interface { + Value() big.Int +} diff --git a/boundedint/int256.go b/boundedint/int256.go index 5160da9fd0..9614c9168b 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -72,12 +72,13 @@ func (u *Int256) Copy(v *Int256) *Int256 { } // Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field -func (u *Int256) Cmp(v *Int256) int { - return u.value.Cmp(&v.value) +func (u *Int256) Cmp(v BoundedInt) int { + value := v.Value() + return u.value.Cmp(&value) } // Equals returns true if the two Int256 structs have the same underlying values, false otherwise -func (u *Int256) Equals(v *Int256) bool { +func (u *Int256) Equals(v BoundedInt) bool { return u.Cmp(v) == 0 } diff --git a/boundedint/uint256.go b/boundedint/uint256.go index d5f588bc33..1f23a2ceaa 100644 --- a/boundedint/uint256.go +++ b/boundedint/uint256.go @@ -72,12 +72,13 @@ func (u *Uint256) Copy(v *Uint256) *Uint256 { } // Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field -func (u *Uint256) Cmp(v *Uint256) int { - return u.value.Cmp(&v.value) +func (u *Uint256) Cmp(v BoundedInt) int { + value := v.Value() + return u.value.Cmp(&value) } // Equals returns true if the two Uint256 structs have the same underlying values, false otherwise -func (u *Uint256) Equals(v *Uint256) bool { +func (u *Uint256) Equals(v BoundedInt) bool { return u.Cmp(v) == 0 } diff --git a/cmd/swarm/config.go b/cmd/swarm/config.go index cf1499dadb..6cc78777cb 100644 --- a/cmd/swarm/config.go +++ b/cmd/swarm/config.go @@ -35,6 +35,7 @@ import ( "github.com/naoina/toml" bzzapi "github.com/ethersphere/swarm/api" + "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/network" ) @@ -219,10 +220,10 @@ func flagsOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Confi currentConfig.SwapDepositAmount = deposit } if paymentThreshold := ctx.GlobalUint64(SwarmSwapPaymentThresholdFlag.Name); paymentThreshold != 0 { - currentConfig.SwapPaymentThreshold = paymentThreshold + currentConfig.SwapPaymentThreshold = boundedint.Uint64ToUint256(paymentThreshold) } if disconnectThreshold := ctx.GlobalUint64(SwarmSwapDisconnectThresholdFlag.Name); disconnectThreshold != 0 { - currentConfig.SwapDisconnectThreshold = disconnectThreshold + currentConfig.SwapDisconnectThreshold = boundedint.Uint64ToUint256(disconnectThreshold) } if ctx.GlobalIsSet(SwarmNoSyncFlag.Name) { val := !ctx.GlobalBool(SwarmNoSyncFlag.Name) diff --git a/swap/api.go b/swap/api.go index 5d354dc376..cbb264f5ec 100644 --- a/swap/api.go +++ b/swap/api.go @@ -26,8 +26,8 @@ func (s *Swap) APIs() []rpc.API { type swapAPI interface { AvailableBalance() (*boundedint.Uint256, error) - PeerBalance(peer enode.ID) (int64, error) - Balances() (map[enode.ID]int64, error) + PeerBalance(peer enode.ID) (*boundedint.Int256, error) + Balances() (map[enode.ID]*boundedint.Int256, error) PeerCheques(peer enode.ID) (PeerCheques, error) Cheques() (map[enode.ID]*PeerCheques, error) } @@ -95,7 +95,7 @@ func (s *Swap) AvailableBalance() (*boundedint.Uint256, error) { } // PeerBalance returns the balance for a given peer -func (s *Swap) PeerBalance(peer enode.ID) (balance int64, err error) { +func (s *Swap) PeerBalance(peer enode.ID) (balance *boundedint.Int256, err error) { if swapPeer := s.getPeer(peer); swapPeer != nil { return swapPeer.getBalance(), nil } @@ -104,8 +104,8 @@ func (s *Swap) PeerBalance(peer enode.ID) (balance int64, err error) { } // Balances returns the balances for all known SWAP peers -func (s *Swap) Balances() (map[enode.ID]int64, error) { - balances := make(map[enode.ID]int64) +func (s *Swap) Balances() (map[enode.ID]*boundedint.Int256, error) { + balances := make(map[enode.ID]*boundedint.Int256) s.peersLock.Lock() for peer, swapPeer := range s.peers { @@ -119,7 +119,7 @@ func (s *Swap) Balances() (map[enode.ID]int64, error) { balanceIterFunction := func(key []byte, value []byte) (stop bool, err error) { peer := keyToID(string(key), balancePrefix) if _, peerHasBalance := balances[peer]; !peerHasBalance { - var peerBalance int64 + var peerBalance *boundedint.Int256 err = json.Unmarshal(value, &peerBalance) if err == nil { balances[peer] = peerBalance diff --git a/swap/config.go b/swap/config.go index ab645d0a89..f06f5469ea 100644 --- a/swap/config.go +++ b/swap/config.go @@ -18,6 +18,8 @@ package swap import ( "time" + + "github.com/ethersphere/swarm/boundedint" ) // These are currently arbitrary values which have not been verified nor tested @@ -25,8 +27,8 @@ import ( const ( // Thresholds which trigger payment or disconnection. The unit is in honey (internal accounting unit) // DefaultPaymentThreshold is set to be equivalent to requesting and serving 10mb of data (2441 chunks (4096 bytes) = 10 mb, 10^7 bytes = 10 mb) - DefaultPaymentThreshold = 2441*RetrieveRequestPrice + (10^7)*ChunkDeliveryPrice // 4096 * 2441 = 10 mb, - DefaultDisconnectThreshold = 20 * DefaultPaymentThreshold + defaultPaymentThreshold = 2441*RetrieveRequestPrice + (10^7)*ChunkDeliveryPrice // 4096 * 2441 = 10 mb, + defaultDisconnectThreshold = 20 * defaultPaymentThreshold // DefaultDepositAmount is the default amount to send to the contract when initially deploying // NOTE: deliberate value for now; needs experimentation DefaultDepositAmount = 0 @@ -37,3 +39,6 @@ const ( AllowedNetworkID = 5 DefaultTransactionTimeout = 10 * time.Minute ) + +var DefaultPaymentThreshold = *boundedint.Uint64ToUint256(defaultPaymentThreshold) +var DefaultDisconnectThreshold = *boundedint.Uint64ToUint256(defaultDisconnectThreshold) diff --git a/swap/peer.go b/swap/peer.go index 8bf8e8e071..70e69f4874 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -20,7 +20,7 @@ import ( "context" "errors" "fmt" - "strconv" + "math/big" "sync" "github.com/ethereum/go-ethereum/common" @@ -38,13 +38,13 @@ type Peer struct { *protocols.Peer lock sync.RWMutex swap *Swap - beneficiary common.Address // address of the peers chequebook owner - contractAddress common.Address // address of the peers chequebook - lastReceivedCheque *Cheque // last cheque we received from the peer - lastSentCheque *Cheque // last cheque that was sent to peer that was confirmed - pendingCheque *Cheque // last cheque that was sent to peer but is not yet confirmed - balance int64 // current balance of the peer - logger log.Logger // logger for swap related messages and audit trail with peer identifier + beneficiary common.Address // address of the peers chequebook owner + contractAddress common.Address // address of the peers chequebook + lastReceivedCheque *Cheque // last cheque we received from the peer + lastSentCheque *Cheque // last cheque that was sent to peer that was confirmed + pendingCheque *Cheque // last cheque that was sent to peer but is not yet confirmed + balance *boundedint.Int256 // current balance of the peer + logger log.Logger // logger for swap related messages and audit trail with peer identifier } // NewPeer creates a new swap Peer instance @@ -126,26 +126,29 @@ func (p *Peer) getLastSentCumulativePayout() *boundedint.Uint256 { } // the caller is expected to hold p.lock -func (p *Peer) setBalance(balance int64) error { +func (p *Peer) setBalance(balance *boundedint.Int256) error { p.balance = balance return p.swap.saveBalance(p.ID(), balance) } // getBalance returns the current balance for this peer // the caller is expected to hold p.lock -func (p *Peer) getBalance() int64 { +func (p *Peer) getBalance() *boundedint.Int256 { return p.balance } // the caller is expected to hold p.lock -func (p *Peer) updateBalance(amount int64) error { +func (p *Peer) updateBalance(amount *boundedint.Int256) error { //adjust the balance //if amount is negative, it will decrease, otherwise increase - newBalance := p.getBalance() + amount + newBalance, err := boundedint.NewInt256().Add(p.getBalance(), amount) + if err != nil { + return err + } if err := p.setBalance(newBalance); err != nil { return err } - p.logger.Debug("updated balance", "balance", strconv.FormatInt(newBalance, 10)) + p.logger.Debug("updated balance", "balance", newBalance) return nil } @@ -157,11 +160,13 @@ func (p *Peer) createCheque() (*Cheque, error) { var cheque *Cheque var err error - if p.getBalance() >= 0 { + if p.getBalance().Cmp(boundedint.Int64ToInt256(0)) >= 0 { return nil, fmt.Errorf("expected negative balance, found: %d", p.getBalance()) } // the balance should be negative here, we take the absolute value: - honey := uint64(-p.getBalance()) + b := p.getBalance().Value() + balance := new(big.Int).Mul(&b, big.NewInt(-1)) + honey := balance.Uint64() oraclePrice, err := p.swap.honeyPriceOracle.GetPrice(honey) if err != nil { @@ -209,14 +214,14 @@ func (p *Peer) sendCheque() error { return fmt.Errorf("error while saving pending cheque: %v", err) } - honeyAmount := int64(cheque.Honey) + honeyAmount := boundedint.Int64ToInt256(int64(cheque.Honey)) err = p.updateBalance(honeyAmount) if err != nil { return fmt.Errorf("error while creating cheque: %v", err) } metrics.GetOrRegisterCounter("swap.cheques.emitted.num", nil).Inc(1) - metrics.GetOrRegisterCounter("swap.cheques.emitted.honey", nil).Inc(honeyAmount) + metrics.GetOrRegisterCounter("swap.cheques.emitted.honey", nil).Inc(int64(cheque.Honey)) p.logger.Info("sending cheque to peer", "cheque", cheque) return p.Send(context.Background(), &EmitChequeMsg{ diff --git a/swap/swap.go b/swap/swap.go index b6bd321804..0a4278414b 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -78,10 +78,10 @@ type Owner struct { // Params encapsulates economic and operational parameters type Params struct { - BaseAddrs *network.BzzAddr // this node's base address - LogPath string // optional audit log path - PaymentThreshold int64 // honey amount at which a payment is triggered - DisconnectThreshold int64 // honey amount at which a peer disconnects + BaseAddrs *network.BzzAddr // this node's base address + LogPath string // optional audit log path + PaymentThreshold *boundedint.Uint256 // honey amount at which a payment is triggered + DisconnectThreshold *boundedint.Uint256 // honey amount at which a peer disconnects } // newSwapLogger returns a new logger for standard swap logs @@ -172,7 +172,7 @@ func New(dbPath string, prvkey *ecdsa.PrivateKey, backendURL string, params *Par if stateStore, err = state.NewDBStore(filepath.Join(dbPath, "swap.db")); err != nil { return nil, fmt.Errorf("initializing statestore: %w", err) } - if params.DisconnectThreshold <= params.PaymentThreshold { + if params.DisconnectThreshold.Cmp(params.PaymentThreshold) < 1 { return nil, fmt.Errorf("disconnect threshold lower or at payment threshold. DisconnectThreshold: %d, PaymentThreshold: %d", params.DisconnectThreshold, params.PaymentThreshold) } // connect to the backend @@ -317,10 +317,10 @@ func createOwner(prvkey *ecdsa.PrivateKey) *Owner { } // modifyBalanceOk checks that the amount would not result in crossing the disconnection threshold -func (s *Swap) modifyBalanceOk(amount int64, swapPeer *Peer) (err error) { +func (s *Swap) modifyBalanceOk(amount *boundedint.Int256, swapPeer *Peer) (err error) { // check if balance with peer is over the disconnect threshold and if the message would increase the existing debt balance := swapPeer.getBalance() - if balance >= s.params.DisconnectThreshold && amount > 0 { + if balance.Cmp(s.params.DisconnectThreshold) >= 0 && amount.Cmp(boundedint.Int64ToInt256(0)) > 0 { return fmt.Errorf("balance for peer %s is over the disconnect threshold %d and cannot incur more debt, disconnecting", swapPeer.ID().String(), s.params.DisconnectThreshold) } @@ -339,7 +339,7 @@ func (s *Swap) Check(amount int64, peer *protocols.Peer) (err error) { swapPeer.lock.Lock() defer swapPeer.lock.Unlock() // currently this is the only real check needed: - return s.modifyBalanceOk(amount, swapPeer) + return s.modifyBalanceOk(boundedint.Int64ToInt256(amount), swapPeer) } // Add is the (sole) accounting function @@ -353,11 +353,11 @@ func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error) { swapPeer.lock.Lock() defer swapPeer.lock.Unlock() // we should probably check here again: - if err = s.modifyBalanceOk(amount, swapPeer); err != nil { + if err = s.modifyBalanceOk(boundedint.Int64ToInt256(amount), swapPeer); err != nil { return err } - if err = swapPeer.updateBalance(amount); err != nil { + if err = swapPeer.updateBalance(boundedint.Int64ToInt256(amount)); err != nil { return err } @@ -369,7 +369,19 @@ func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error) { // that the balance is *below* the threshold // the caller is expected to hold swapPeer.lock func (s *Swap) checkPaymentThresholdAndSendCheque(swapPeer *Peer) error { - if swapPeer.getBalance() <= -s.params.PaymentThreshold { + balance := swapPeer.getBalance() + thresholdValue := s.params.PaymentThreshold.Value() + threshold, err := boundedint.NewInt256().Set(thresholdValue) + if err != nil { + return err + } + + negativeThreshold, err := boundedint.NewInt256().Mul(boundedint.Int64ToInt256(-1), threshold) + if err != nil { + return err + } + + if balance.Cmp(negativeThreshold) < 1 { swapPeer.logger.Info("balance for peer went over the payment threshold, sending cheque", "payment threshold", s.params.PaymentThreshold) return swapPeer.sendCheque() } @@ -417,14 +429,19 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque // reset balance by amount // as this is done by the creditor, receiving the cheque, the amount should be negative, // so that updateBalance will calculate balance + amount which result in reducing the peer's balance - honeyAmount := int64(cheque.Honey) - err = p.updateBalance(-honeyAmount) + honeyAmount := boundedint.Int64ToInt256(int64(cheque.Honey)) + honey, err := boundedint.NewInt256().Mul(boundedint.Int64ToInt256(-1), honeyAmount) + if err != nil { + return protocols.Break(err) + } + + err = p.updateBalance(honey) if err != nil { return protocols.Break(fmt.Errorf("updating balance: %w", err)) } metrics.GetOrRegisterCounter("swap.cheques.received.num", nil).Inc(1) - metrics.GetOrRegisterCounter("swap.cheques.received.honey", nil).Inc(honeyAmount) + metrics.GetOrRegisterCounter("swap.cheques.received.honey", nil).Inc(int64(cheque.Honey)) err = p.Send(ctx, &ConfirmChequeMsg{ Cheque: cheque, @@ -561,13 +578,13 @@ func (s *Swap) loadPendingCheque(p enode.ID) (cheque *Cheque, err error) { // loadBalance loads the current balance for the peer from the store // and returns 0 if there was no prior balance saved -func (s *Swap) loadBalance(p enode.ID) (balance int64, err error) { +func (s *Swap) loadBalance(p enode.ID) (balance *boundedint.Int256, err error) { err = s.store.Get(balanceKey(p), &balance) if err == state.ErrNotFound { - return 0, nil + return boundedint.Int64ToInt256(0), nil } if err != nil { - return 0, err + return boundedint.Int64ToInt256(0), err } return balance, nil } @@ -588,7 +605,7 @@ func (s *Swap) savePendingCheque(p enode.ID, cheque *Cheque) error { } // saveBalance saves balance as the current balance for peer -func (s *Swap) saveBalance(p enode.ID, balance int64) error { +func (s *Swap) saveBalance(p enode.ID, balance *boundedint.Int256) error { return s.store.Put(balanceKey(p), balance) } diff --git a/swarm.go b/swarm.go index 774664b684..cb74764b32 100644 --- a/swarm.go +++ b/swarm.go @@ -137,8 +137,8 @@ func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err e swapParams := &swap.Params{ BaseAddrs: bzzconfig.Address, LogPath: self.config.SwapLogPath, - DisconnectThreshold: int64(self.config.SwapDisconnectThreshold), - PaymentThreshold: int64(self.config.SwapPaymentThreshold), + DisconnectThreshold: self.config.SwapDisconnectThreshold, + PaymentThreshold: self.config.SwapPaymentThreshold, } // create the accounting objects From ec696e87d59d4cfe8f199d752f13f5cd1500fa5a Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 3 Feb 2020 17:29:06 -0300 Subject: [PATCH 11/70] swap: fix compile errors in api test --- swap/api_test.go | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/swap/api_test.go b/swap/api_test.go index 0bd51ced71..302c080181 100644 --- a/swap/api_test.go +++ b/swap/api_test.go @@ -7,6 +7,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/simulations/adapters" + "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" ) @@ -40,19 +41,19 @@ func TestPeerBalance(t *testing.T) { defer clean() // test balance - setBalance(t, testPeer, 888) - testPeerBalance(t, swap, testPeerID, 888) + setBalance(t, testPeer, boundedint.Int64ToInt256(888)) + testPeerBalance(t, swap, testPeerID, boundedint.Int64ToInt256(888)) // test balance after change - setBalance(t, testPeer, 17000) - testPeerBalance(t, swap, testPeerID, 17000) + setBalance(t, testPeer, boundedint.Int64ToInt256(17000)) + testPeerBalance(t, swap, testPeerID, boundedint.Int64ToInt256(17000)) // test balance for second peer testPeer2 := addPeer(t, swap) testPeer2ID := testPeer2.ID() - setBalance(t, testPeer2, 4) - testPeerBalance(t, swap, testPeer2ID, 4) + setBalance(t, testPeer2, boundedint.Int64ToInt256(4)) + testPeerBalance(t, swap, testPeer2ID, boundedint.Int64ToInt256(4)) // test balance for inexistent node invalidPeerID := adapters.RandomNodeConfig().ID @@ -67,22 +68,22 @@ func TestPeerBalance(t *testing.T) { // test balance for disconnected node testPeer3 := newDummyPeer().Peer testPeer3ID := testPeer3.ID() - err = swap.saveBalance(testPeer3ID, 777) - testPeerBalance(t, swap, testPeer3ID, 777) + err = swap.saveBalance(testPeer3ID, boundedint.Int64ToInt256(777)) + testPeerBalance(t, swap, testPeer3ID, boundedint.Int64ToInt256(777)) // test previous results are still correct - testPeerBalance(t, swap, testPeerID, 17000) - testPeerBalance(t, swap, testPeer2ID, 4) + testPeerBalance(t, swap, testPeerID, boundedint.Int64ToInt256(17000)) + testPeerBalance(t, swap, testPeer2ID, boundedint.Int64ToInt256(4)) } // tests that expected balance for peer matches the result of the Balance function -func testPeerBalance(t *testing.T, s *Swap, id enode.ID, expectedBalance int64) { +func testPeerBalance(t *testing.T, s *Swap, id enode.ID, expectedBalance *boundedint.Int256) { t.Helper() b, err := s.PeerBalance(id) if err != nil { t.Fatal(err) } - if b != expectedBalance { + if !b.Equals(expectedBalance) { t.Fatalf("Expected peer's balance to be %d, but is %d", expectedBalance, b) } } @@ -97,7 +98,7 @@ func addPeer(t *testing.T, s *Swap) *Peer { } // sets the given balance for the given peer, fails if there are errors -func setBalance(t *testing.T, p *Peer, balance int64) { +func setBalance(t *testing.T, p *Peer, balance *boundedint.Int256) { t.Helper() err := p.setBalance(balance) if err != nil { @@ -119,7 +120,7 @@ func TestBalances(t *testing.T) { testPeerID := testPeer.ID() // test balances with one peer - setBalance(t, testPeer, 808) + setBalance(t, testPeer, boundedint.Int64ToInt256(808)) testBalances(t, swap, map[enode.ID]int64{testPeerID: 808}) // add second peer @@ -127,11 +128,11 @@ func TestBalances(t *testing.T) { testPeer2ID := testPeer2.ID() // test balances with second peer - setBalance(t, testPeer2, 123) + setBalance(t, testPeer2, boundedint.Int64ToInt256(123)) testBalances(t, swap, map[enode.ID]int64{testPeerID: 808, testPeer2ID: 123}) // test balances after balance change for peer - setBalance(t, testPeer, 303) + setBalance(t, testPeer, boundedint.Int64ToInt256(303)) testBalances(t, swap, map[enode.ID]int64{testPeerID: 303, testPeer2ID: 123}) } From 440e4c689ba7d305d93e70e5bf6671c254155139 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 4 Feb 2020 15:22:34 -0300 Subject: [PATCH 12/70] swap: fix compile errors in protocol test --- swap/common_test.go | 4 +-- swap/protocol_test.go | 74 +++++++++++++++++++++++++++++-------------- 2 files changed, 52 insertions(+), 26 deletions(-) diff --git a/swap/common_test.go b/swap/common_test.go index 63e805d910..8dc626085f 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -88,8 +88,8 @@ func newDefaultParams(t *testing.T) *Params { return &Params{ BaseAddrs: network.NewBzzAddr(baseKey, nil), LogPath: "", - PaymentThreshold: int64(DefaultPaymentThreshold), - DisconnectThreshold: int64(DefaultDisconnectThreshold), + PaymentThreshold: &DefaultPaymentThreshold, + DisconnectThreshold: &DefaultDisconnectThreshold, } } diff --git a/swap/protocol_test.go b/swap/protocol_test.go index b451b4c36d..b96bafba28 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -261,7 +261,7 @@ func TestEmitCheque(t *testing.T) { debitor := creditorSwap.getPeer(protocolTester.Nodes[0].ID()) // set balance artificially - if err = debitor.setBalance(balanceValue.Int64()); err != nil { + if err = debitor.setBalance(boundedint.Int64ToInt256(100001)); err != nil { t.Fatal(err) } @@ -308,7 +308,7 @@ func TestEmitCheque(t *testing.T) { } // check that the balance has been reset - if debitor.getBalance() != 0 { + if debitor.getBalance().Cmp(boundedint.Int64ToInt256(0)) != 0 { t.Fatalf("Expected debitor balance to have been reset to %d, but it is %d", 0, debitor.getBalance()) } recvCheque := debitor.getLastReceivedCheque() @@ -333,7 +333,12 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.Uint64ToUint256(DefaultPaymentThreshold*2)) + depositAmount, err := boundedint.NewUint256().Mul(&DefaultPaymentThreshold, boundedint.Uint64ToUint256(2)) + if err != nil { + t.Fatal(err) + } + + protocolTester, clean, err := newSwapTester(t, testBackend, depositAmount) defer clean() if err != nil { t.Fatal(err) @@ -356,22 +361,34 @@ func TestTriggerPaymentThreshold(t *testing.T) { creditor := debitorSwap.getPeer(protocolTester.Nodes[0].ID()) // set the balance to manually be at PaymentThreshold - overDraft := 42 - expectedAmount := uint64(overDraft) + DefaultPaymentThreshold - creditor.setBalance(-int64(DefaultPaymentThreshold)) + overDraft := boundedint.Uint64ToUint256(42) + expectedAmount, err := boundedint.NewUint256().Add(overDraft, &DefaultPaymentThreshold) + if err != nil { + t.Fatal(err) + } + + pt, err := boundedint.NewInt256().Set(DefaultPaymentThreshold.Value()) + if err != nil { + t.Fatal(err) + } + b, err := boundedint.NewInt256().Mul(boundedint.Int64ToInt256(-1), pt) + if err != nil { + t.Fatal(err) + } + creditor.setBalance(b) // we expect a cheque at the end of the test, but not yet if creditor.getLastSentCheque() != nil { t.Fatalf("Expected no cheques yet, but there is %v:", creditor.getLastSentCheque()) } // do some accounting, no error expected, just a WARN - err = debitorSwap.Add(int64(-overDraft), creditor.Peer) + err = debitorSwap.Add(-42, creditor.Peer) if err != nil { t.Fatal(err) } // balance should be reset now - if creditor.getBalance() != 0 { + if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) } @@ -381,11 +398,12 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal("Expected pending cheque") } - if !pending.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedAmount)) { + if !pending.CumulativePayout.Equals(expectedAmount) { t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) } - if pending.Honey != expectedAmount { + ea := expectedAmount.Value() + if pending.Honey != (&ea).Uint64() { t.Fatalf("Expected cheque honey to be %d, but is %d", expectedAmount, pending.Honey) } @@ -444,12 +462,13 @@ loop: } // because no other accounting took place in the meantime the balance should be exactly 0 - if creditor.getBalance() != 0 { + if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) } // do some accounting again to trigger a second cheque - if err = debitorSwap.Add(-int64(DefaultPaymentThreshold), creditor.Peer); err != nil { + amount := DefaultPaymentThreshold.Value() + if err = debitorSwap.Add(-(amount.Int64()), creditor.Peer); err != nil { t.Fatal(err) } @@ -469,7 +488,7 @@ loop: t.Fatal(err) } - if creditor.getBalance() != 0 { + if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) } } @@ -491,7 +510,10 @@ func TestTriggerDisconnectThreshold(t *testing.T) { // set the balance to manually be at DisconnectThreshold overDraft := 42 - expectedBalance := int64(DefaultDisconnectThreshold) + expectedBalance, err := boundedint.NewInt256().Set((&DefaultDisconnectThreshold).Value()) + if err != nil { + t.Fatal(err) + } // we don't expect any change after the test debitor.setBalance(expectedBalance) // we also don't expect any cheques yet @@ -572,11 +594,11 @@ func TestSwapRPC(t *testing.T) { id2 := dummyPeer2.ID() // set some fake balances - fakeBalance1 := int64(234) - fakeBalance2 := int64(-100) + fakeBalance1 := boundedint.Int64ToInt256(234) + fakeBalance2 := boundedint.Int64ToInt256(-100) // query a first time, should give error - var balance int64 + var balance *boundedint.Uint256 err = rpcclient.Call(&balance, "swap_peerBalance", id1) // at this point no balance should be there: no peer registered with Swap if err == nil { @@ -585,7 +607,7 @@ func TestSwapRPC(t *testing.T) { log.Debug("servicenode balance", "balance", balance) // ...thus balance should be zero - if balance != 0 { + if !balance.Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("Expected balance to be 0 but it is %d", balance) } @@ -613,7 +635,7 @@ func TestSwapRPC(t *testing.T) { t.Fatal(err) } log.Debug("balance1", "balance1", balance) - if balance != fakeBalance1 { + if !balance.Equals(fakeBalance1) { t.Fatalf("Expected balance %d to be equal to fake balance %d, but it is not", balance, fakeBalance1) } @@ -622,7 +644,7 @@ func TestSwapRPC(t *testing.T) { t.Fatal(err) } log.Debug("balance2", "balance2", balance) - if balance != fakeBalance2 { + if !balance.Equals(fakeBalance2) { t.Fatalf("Expected balance %d to be equal to fake balance %d, but it is not", balance, fakeBalance2) } @@ -634,13 +656,17 @@ func TestSwapRPC(t *testing.T) { } log.Debug("received balances", "allBalances", allBalances) - var sum int64 + var s int64 for _, v := range allBalances { - sum += v + s += v } + sum := boundedint.Int64ToInt256(s) - fakeSum := fakeBalance1 + fakeBalance2 - if sum != fakeSum { + fakeSum, err := boundedint.NewInt256().Add(fakeBalance1, fakeBalance2) + if err != nil { + t.Fatal(err) + } + if !sum.Equals(fakeSum) { t.Fatalf("Expected total balance to be %d, but it %d", fakeSum, sum) } From 2b81a9e8c3cf46ed47bd9d491efcaeaa950593e7 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 4 Feb 2020 16:12:36 -0300 Subject: [PATCH 13/70] swap: fix compile errors in simulations test --- swap/simulations_test.go | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/swap/simulations_test.go b/swap/simulations_test.go index cbc9eba174..4da219bec6 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -106,9 +106,12 @@ func (m *testMsgByReceiver) Price() *protocols.Price { } } +var paymentThreshold = DefaultPaymentThreshold.Value() +var paymentThresholdPrice = paymentThreshold.Uint64() + func (m *testMsgBigPrice) Price() *protocols.Price { return &protocols.Price{ - Value: DefaultPaymentThreshold + 1, + Value: paymentThresholdPrice + 1, PerByte: false, Payer: protocols.Sender, } @@ -287,7 +290,7 @@ func TestPingPongChequeSimulation(t *testing.T) { counter := cter.(metrics.Counter) counter.Clear() var lastCount int64 - expectedPayout1, expectedPayout2 := DefaultPaymentThreshold+1, DefaultPaymentThreshold+1 + expectedPayout1, expectedPayout2 := paymentThresholdPrice+1, paymentThresholdPrice+1 _, err = sim.AddNodesAndConnectFull(nodeCount) if err != nil { @@ -346,7 +349,7 @@ func TestPingPongChequeSimulation(t *testing.T) { t.Fatal(err) } lastCount += 1 - expectedPayout1 += DefaultPaymentThreshold + 1 + expectedPayout1 += paymentThresholdPrice + 1 } else { if err := p1Peer.Send(context.Background(), &testMsgBigPrice{}); err != nil { t.Fatal(err) @@ -355,7 +358,7 @@ func TestPingPongChequeSimulation(t *testing.T) { t.Fatal(err) } lastCount += 1 - expectedPayout2 += DefaultPaymentThreshold + 1 + expectedPayout2 += paymentThresholdPrice + 1 } } @@ -368,7 +371,7 @@ func TestPingPongChequeSimulation(t *testing.T) { t.Fatal(err) } - expected := uint64(maxCheques) / 2 * (DefaultPaymentThreshold + 1) + expected := uint64(maxCheques) / 2 * (paymentThresholdPrice + 1) if !ch1.CumulativePayout.Equals(boundedint.Uint64ToUint256(expected)) { t.Fatalf("expected cumulative payout to be %d, but is %v", expected, ch1.CumulativePayout) } @@ -416,7 +419,7 @@ func TestMultiChequeSimulation(t *testing.T) { counter := cter.(metrics.Counter) counter.Clear() var lastCount int64 - expectedPayout := DefaultPaymentThreshold + 1 + expectedPayout := paymentThresholdPrice + 1 _, err = sim.AddNodesAndConnectFull(nodeCount) if err != nil { @@ -477,7 +480,7 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatal(err) } lastCount += 1 - expectedPayout += DefaultPaymentThreshold + 1 + expectedPayout += paymentThresholdPrice + 1 } // check balances: @@ -490,7 +493,12 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatal(err) } - if b1 != -b2 { + b2, err = boundedint.NewInt256().Mul(b2, boundedint.Int64ToInt256(-1)) + if err != nil { + t.Fatal(err) + } + + if !b1.Equals(b2) { t.Fatalf("Expected symmetric balances, but they are not: %d vs %d", b1, b2) } // check cheques @@ -508,7 +516,7 @@ func TestMultiChequeSimulation(t *testing.T) { } // check also the actual expected amount - expectedPayout = uint64(maxCheques) * (DefaultPaymentThreshold + 1) + expectedPayout = uint64(maxCheques) * (defaultPaymentThreshold + 1) if !cheque2.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedPayout)) { t.Fatalf("Expected %d in cumulative payout, got %v", expectedPayout, cheque1.CumulativePayout) @@ -685,7 +693,11 @@ func TestBasicSwapSimulation(t *testing.T) { if err != nil { return fmt.Errorf("expected counter balance for node %v to be found, but not found", node) } - if nodeBalanceWithP != -pBalanceWithNode { + pBalanceWithNode, err = boundedint.NewInt256().Mul(pBalanceWithNode, boundedint.Int64ToInt256(-1)) + if err != nil { + return err + } + if !nodeBalanceWithP.Equals(pBalanceWithNode) { return fmt.Errorf("Expected symmetric balances, but they are not: %d vs %d", nodeBalanceWithP, pBalanceWithNode) } } From 0678e50bd064c6b99dd476d76c3a2df81e3b68e8 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 5 Feb 2020 10:45:57 -0300 Subject: [PATCH 14/70] swap: fix compile errors in swap test --- swap/swap_test.go | 99 +++++++++++++++++++++++++++++------------------ 1 file changed, 62 insertions(+), 37 deletions(-) diff --git a/swap/swap_test.go b/swap/swap_test.go index 242b024018..64b33553fe 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -65,7 +65,7 @@ var ( // if `amount` is positive, it means the node which adds this booking will be credited in respect to `peer` // otherwise it will be debited type booking struct { - amount int64 + amount *boundedint.Int256 peer *protocols.Peer } @@ -157,7 +157,7 @@ func TestStoreBalances(t *testing.T) { t.Fatal(err) } testPeerID := testPeer.ID() - peerBalance := int64(29) + peerBalance := boundedint.Int64ToInt256(29) if err := testPeer.setBalance(peerBalance); err != nil { t.Fatal(err) } @@ -170,7 +170,7 @@ func TestStoreBalances(t *testing.T) { t.Fatal(err) } testPeer2ID := testPeer2.ID() - peer2Balance := int64(-76) + peer2Balance := boundedint.Int64ToInt256(-76) if err := testPeer2.setBalance(peer2Balance); err != nil { t.Fatal(err) @@ -180,14 +180,14 @@ func TestStoreBalances(t *testing.T) { comparePeerBalance(t, s, testPeer2ID, peer2Balance) } -func comparePeerBalance(t *testing.T, s *Swap, peer enode.ID, expectedPeerBalance int64) { +func comparePeerBalance(t *testing.T, s *Swap, peer enode.ID, expectedPeerBalance *boundedint.Int256) { t.Helper() - var peerBalance int64 + var peerBalance *boundedint.Int256 err := s.store.Get(balanceKey(peer), &peerBalance) if err != nil && err != state.ErrNotFound { t.Error("Unexpected peer balance retrieval failure.") } - if peerBalance != expectedPeerBalance { + if !peerBalance.Equals(expectedPeerBalance) { t.Errorf("Expected peer store balance to be %d, but is %d instead.", expectedPeerBalance, peerBalance) } } @@ -220,9 +220,9 @@ func TestRepeatedBookings(t *testing.T) { // credits and debits to peer 2 mixedBookings := []booking{ - {int64(mrand.Intn(100)), testPeer2.Peer}, - {int64(0 - mrand.Intn(55)), testPeer2.Peer}, - {int64(0 - mrand.Intn(999)), testPeer2.Peer}, + {boundedint.Int64ToInt256(int64(mrand.Intn(100))), testPeer2.Peer}, + {boundedint.Int64ToInt256(int64(0 - mrand.Intn(55))), testPeer2.Peer}, + {boundedint.Int64ToInt256(int64(0 - mrand.Intn(999))), testPeer2.Peer}, } addBookings(swap, mixedBookings) verifyBookings(t, swap, append(bookings, mixedBookings...)) @@ -314,7 +314,10 @@ func TestNewSwapFailure(t *testing.T) { config.dbPath = dir config.prvkey = prvKey config.backendURL = ipcEndpoint - params.PaymentThreshold = params.DisconnectThreshold + 1 + params.PaymentThreshold, err = boundedint.NewUint256().Add(params.DisconnectThreshold, boundedint.Uint64ToUint256(1)) + if err != nil { + t.Fatal(err) + } config.factoryAddress = testBackend.factoryAddress }, check: func(t *testing.T, config *testSwapConfig) { @@ -364,7 +367,7 @@ func TestNewSwapFailure(t *testing.T) { configure: func(config *testSwapConfig) { config.prvkey = prvKey config.backendURL = "invalid backendURL" - params.PaymentThreshold = int64(DefaultPaymentThreshold) + params.PaymentThreshold = &DefaultPaymentThreshold config.skipDeposit = false config.factoryAddress = testBackend.factoryAddress }, @@ -556,8 +559,9 @@ func TestDisconnectThreshold(t *testing.T) { testPeer := newDummyPeer() swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) + amount := DefaultDisconnectThreshold.Value() // leave balance exactly at disconnect threshold - swap.Add(int64(DefaultDisconnectThreshold), testPeer.Peer) + swap.Add((&amount).Int64(), testPeer.Peer) // account for traffic which increases debt err := swap.Add(1, testPeer.Peer) if err == nil { @@ -577,16 +581,17 @@ func TestDisconnectThreshold(t *testing.T) { func TestPaymentThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, boundedint.Uint64ToUint256(DefaultPaymentThreshold)) + testDeploy(context.Background(), swap, &DefaultPaymentThreshold) testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) - if err := swap.Add(-int64(DefaultPaymentThreshold), testPeer.Peer); err != nil { + amount := DefaultPaymentThreshold.Value() + if err := swap.Add(-(&amount).Int64(), testPeer.Peer); err != nil { t.Fatal() } var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(boundedint.Uint64ToUint256(DefaultPaymentThreshold)) { + if !cheque.CumulativePayout.Equals(&DefaultPaymentThreshold) { t.Fatal() } } @@ -607,14 +612,18 @@ func TestResetBalance(t *testing.T) { defer clean1() defer clean2() - testAmount := DefaultPaymentThreshold + 42 + testAmount, err := boundedint.NewUint256().Add(&DefaultPaymentThreshold, boundedint.Uint64ToUint256(42)) + + if err != nil { + t.Fatal(err) + } ctx := context.Background() - err := testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)) + err = testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, boundedint.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, debitorSwap, testAmount) if err != nil { t.Fatal(err) } @@ -633,9 +642,18 @@ func TestResetBalance(t *testing.T) { t.Fatal(err) } + amount := testAmount.Value() + debitorBalance, err := boundedint.NewInt256().Set(amount) + if err != nil { + t.Fatal(err) + } + creditorBalance, err := boundedint.NewInt256().Set(*new(big.Int).Mul(big.NewInt(-1), &amount)) + if err != nil { + t.Fatal(err) + } // set balances arbitrarily - debitor.setBalance(int64(testAmount)) - creditor.setBalance(int64(-testAmount)) + debitor.setBalance(debitorBalance) + creditor.setBalance(creditorBalance) // setup the wait for mined transaction function for testing cleanup := setupContractTest() @@ -648,7 +666,7 @@ func TestResetBalance(t *testing.T) { Cheque: creditor.getPendingCheque(), }) // the debitor should have already reset its balance - if creditor.getBalance() != 0 { + if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("unexpected balance to be 0, but it is %d", creditor.getBalance()) } @@ -677,7 +695,7 @@ func TestResetBalance(t *testing.T) { t.Fatalf("Timeout waiting for cash transactions to complete") } // finally check that the creditor also successfully reset the balances - if debitor.getBalance() != 0 { + if !debitor.getBalance().Equals(boundedint.Int64ToInt256(0)) { t.Fatalf("unexpected balance to be 0, but it is %d", debitor.getBalance()) } } @@ -695,7 +713,7 @@ func testPeerBookings(t *testing.T, s *Swap, bookings *[]booking, bookingAmount // generate as many bookings as specified by `quantity`, each one with the indicated `amount` and `peer` func generateBookings(amount int64, quantity int, peer *protocols.Peer) (bookings []booking) { for i := 0; i < quantity; i++ { - bookings = append(bookings, booking{amount, peer}) + bookings = append(bookings, booking{boundedint.Int64ToInt256(amount), peer}) } return } @@ -704,7 +722,8 @@ func generateBookings(amount int64, quantity int, peer *protocols.Peer) (booking func addBookings(swap *Swap, bookings []booking) { for i := 0; i < len(bookings); i++ { booking := bookings[i] - swap.Add(booking.amount, booking.peer) + amount := booking.amount.Value() + swap.Add(amount.Int64(), booking.peer) } } @@ -722,7 +741,7 @@ func verifyBookings(t *testing.T, s *Swap, bookings []booking) { } // converts a balance map to a one-line string representation -func stringifyBalance(balance map[enode.ID]int64) string { +func stringifyBalance(balance map[enode.ID]*boundedint.Int256) string { marshaledBalance, err := json.Marshal(balance) if err != nil { return err.Error() @@ -733,15 +752,15 @@ func stringifyBalance(balance map[enode.ID]int64) string { // take a swap struct and a list of bookings, and calculate the expected balances. // the result is a map which stores the balance for all the peers present in the bookings, // from the perspective of the node that loaded the Swap struct. -func calculateExpectedBalances(swap *Swap, bookings []booking) map[enode.ID]int64 { - expectedBalances := make(map[enode.ID]int64) +func calculateExpectedBalances(swap *Swap, bookings []booking) map[enode.ID]*boundedint.Int256 { + expectedBalances := make(map[enode.ID]*boundedint.Int256) for i := 0; i < len(bookings); i++ { booking := bookings[i] peerID := booking.peer.ID() peerBalance := expectedBalances[peerID] // peer balance should only be affected if debt is being reduced or if balance is smaller than disconnect threshold - if peerBalance < swap.params.DisconnectThreshold || booking.amount < 0 { - peerBalance += booking.amount + if peerBalance.Cmp(swap.params.DisconnectThreshold) < 0 || booking.amount.Cmp(boundedint.Int64ToInt256(0)) < 0 { + peerBalance.Add(peerBalance, booking.amount) } expectedBalances[peerID] = peerBalance } @@ -766,7 +785,7 @@ func TestRestoreBalanceFromStateStore(t *testing.T) { if err != nil { t.Fatal(err) } - testPeer.setBalance(-8888) + testPeer.setBalance(boundedint.Int64ToInt256(-8888)) tmpBalance := testPeer.getBalance() swap.store.Put(testPeer.ID().String(), &tmpBalance) @@ -783,11 +802,11 @@ func TestRestoreBalanceFromStateStore(t *testing.T) { t.Fatal(err) } - var newBalance int64 + var newBalance *boundedint.Int256 stateStore.Get(testPeer.Peer.ID().String(), &newBalance) // compare the balances - if tmpBalance != newBalance { + if !tmpBalance.Equals(newBalance) { t.Fatalf("Unexpected balance value after sending cheap message test. Expected balance: %d, balance is: %d", tmpBalance, newBalance) } } @@ -1194,10 +1213,13 @@ func TestSwapLogToFile(t *testing.T) { } defer clean() - testAmount := DefaultPaymentThreshold + 42 + testAmount, err := boundedint.NewUint256().Add(&DefaultPaymentThreshold, boundedint.Uint64ToUint256(42)) + if err != nil { + t.Fatal(err) + } ctx := context.Background() - err = testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, creditorSwap, testAmount) if err != nil { t.Fatal(err) } @@ -1220,9 +1242,12 @@ func TestSwapLogToFile(t *testing.T) { t.Fatal(err) } + ta := testAmount.Value() + debitorAmount, err := boundedint.NewInt256().Set(ta) + creditorAmount, err := boundedint.NewInt256().Set(*new(big.Int).Mul(big.NewInt(-1), &ta)) // set balances arbitrarily - debitor.setBalance(int64(testAmount)) - creditor.setBalance(int64(-testAmount)) + debitor.setBalance(debitorAmount) + creditor.setBalance(creditorAmount) // setup the wait for mined transaction function for testing cleanup := setupContractTest() @@ -1333,7 +1358,7 @@ func TestAvailableBalance(t *testing.T) { // send a cheque worth 42 chequeAmount := uint64(42) // create a dummy peer. Note: the peer's contract address and the peers address are resp the swap contract and the swap owner - peer.setBalance(int64(-chequeAmount)) + peer.setBalance(boundedint.Int64ToInt256(int64(-chequeAmount))) if err = peer.sendCheque(); err != nil { t.Fatal(err) } From 0cfebfea82e0dccd103101b451295e8e5686c34f Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 5 Feb 2020 12:27:42 -0300 Subject: [PATCH 15/70] swap: fix linter errors --- swap/api_test.go | 4 ++-- swap/peer.go | 2 +- swap/protocol_test.go | 24 ++++++++++++------------ swap/simulations_test.go | 4 ++-- swap/swap.go | 4 ++-- swap/swap_test.go | 8 ++++---- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/swap/api_test.go b/swap/api_test.go index 302c080181..570712dd34 100644 --- a/swap/api_test.go +++ b/swap/api_test.go @@ -84,7 +84,7 @@ func testPeerBalance(t *testing.T, s *Swap, id enode.ID, expectedBalance *bounde t.Fatal(err) } if !b.Equals(expectedBalance) { - t.Fatalf("Expected peer's balance to be %d, but is %d", expectedBalance, b) + t.Fatalf("Expected peer's balance to be %v, but is %v", expectedBalance, b) } } @@ -144,7 +144,7 @@ func testBalances(t *testing.T, s *Swap, expectedBalances map[enode.ID]int64) { t.Fatal(err) } if !reflect.DeepEqual(actualBalances, expectedBalances) { - t.Fatalf("Expected node's balances to be %d, but are %d", expectedBalances, actualBalances) + t.Fatalf("Expected node's balances to be %v, but are %v", expectedBalances, actualBalances) } } diff --git a/swap/peer.go b/swap/peer.go index 70e69f4874..baa9ae256f 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -161,7 +161,7 @@ func (p *Peer) createCheque() (*Cheque, error) { var err error if p.getBalance().Cmp(boundedint.Int64ToInt256(0)) >= 0 { - return nil, fmt.Errorf("expected negative balance, found: %d", p.getBalance()) + return nil, fmt.Errorf("expected negative balance, found: %v", p.getBalance()) } // the balance should be negative here, we take the absolute value: b := p.getBalance().Value() diff --git a/swap/protocol_test.go b/swap/protocol_test.go index b96bafba28..ed5f52eb9b 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -309,7 +309,7 @@ func TestEmitCheque(t *testing.T) { // check that the balance has been reset if debitor.getBalance().Cmp(boundedint.Int64ToInt256(0)) != 0 { - t.Fatalf("Expected debitor balance to have been reset to %d, but it is %d", 0, debitor.getBalance()) + t.Fatalf("Expected debitor balance to have been reset to %d, but it is %v", 0, debitor.getBalance()) } recvCheque := debitor.getLastReceivedCheque() log.Debug("expected cheque", "cheque", recvCheque) @@ -389,7 +389,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { // balance should be reset now if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) + t.Fatalf("Expected debitorSwap balance to be 0, but is %v", creditor.getBalance()) } // pending cheque should now be set @@ -399,12 +399,12 @@ func TestTriggerPaymentThreshold(t *testing.T) { } if !pending.CumulativePayout.Equals(expectedAmount) { - t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) + t.Fatalf("Expected cheque cumulative payout to be %v, but is %v", expectedAmount, pending.CumulativePayout) } ea := expectedAmount.Value() if pending.Honey != (&ea).Uint64() { - t.Fatalf("Expected cheque honey to be %d, but is %d", expectedAmount, pending.Honey) + t.Fatalf("Expected cheque honey to be %v, but is %v", expectedAmount, pending.Honey) } if pending.Beneficiary != creditor.beneficiary { @@ -463,7 +463,7 @@ loop: // because no other accounting took place in the meantime the balance should be exactly 0 if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) + t.Fatalf("Expected debitorSwap balance to be 0, but is %v", creditor.getBalance()) } // do some accounting again to trigger a second cheque @@ -489,7 +489,7 @@ loop: } if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("Expected debitorSwap balance to be 0, but is %d", creditor.getBalance()) + t.Fatalf("Expected debitorSwap balance to be 0, but is %v", creditor.getBalance()) } } @@ -528,7 +528,7 @@ func TestTriggerDisconnectThreshold(t *testing.T) { } // no balance change expected if debitor.getBalance() != expectedBalance { - t.Fatalf("Expected balance to be %d, but is %d", expectedBalance, debitor.getBalance()) + t.Fatalf("Expected balance to be %v, but is %v", expectedBalance, debitor.getBalance()) } // still no cheques expected if debitor.getPendingCheque() != nil { @@ -542,7 +542,7 @@ func TestTriggerDisconnectThreshold(t *testing.T) { } if debitor.getBalance() != expectedBalance { - t.Fatalf("Expected balance to be %d, but is %d", expectedBalance, debitor.getBalance()) + t.Fatalf("Expected balance to be %v, but is %v", expectedBalance, debitor.getBalance()) } if debitor.getPendingCheque() != nil { @@ -608,7 +608,7 @@ func TestSwapRPC(t *testing.T) { // ...thus balance should be zero if !balance.Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("Expected balance to be 0 but it is %d", balance) + t.Fatalf("Expected balance to be 0 but it is %v", balance) } peer1, err := swap.addPeer(dummyPeer1.Peer, common.Address{}, common.Address{}) @@ -636,7 +636,7 @@ func TestSwapRPC(t *testing.T) { } log.Debug("balance1", "balance1", balance) if !balance.Equals(fakeBalance1) { - t.Fatalf("Expected balance %d to be equal to fake balance %d, but it is not", balance, fakeBalance1) + t.Fatalf("Expected balance %v to be equal to fake balance %v, but it is not", balance, fakeBalance1) } err = rpcclient.Call(&balance, "swap_peerBalance", id2) @@ -645,7 +645,7 @@ func TestSwapRPC(t *testing.T) { } log.Debug("balance2", "balance2", balance) if !balance.Equals(fakeBalance2) { - t.Fatalf("Expected balance %d to be equal to fake balance %d, but it is not", balance, fakeBalance2) + t.Fatalf("Expected balance %v to be equal to fake balance %v, but it is not", balance, fakeBalance2) } // now call all balances @@ -667,7 +667,7 @@ func TestSwapRPC(t *testing.T) { t.Fatal(err) } if !sum.Equals(fakeSum) { - t.Fatalf("Expected total balance to be %d, but it %d", fakeSum, sum) + t.Fatalf("Expected total balance to be %v, but it %v", fakeSum, sum) } balances, err := swap.Balances() diff --git a/swap/simulations_test.go b/swap/simulations_test.go index 4da219bec6..ebb6e49a60 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -499,7 +499,7 @@ func TestMultiChequeSimulation(t *testing.T) { } if !b1.Equals(b2) { - t.Fatalf("Expected symmetric balances, but they are not: %d vs %d", b1, b2) + t.Fatalf("Expected symmetric balances, but they are not: %v vs %v", b1, b2) } // check cheques var cheque1, cheque2 *Cheque @@ -698,7 +698,7 @@ func TestBasicSwapSimulation(t *testing.T) { return err } if !nodeBalanceWithP.Equals(pBalanceWithNode) { - return fmt.Errorf("Expected symmetric balances, but they are not: %d vs %d", nodeBalanceWithP, pBalanceWithNode) + return fmt.Errorf("Expected symmetric balances, but they are not: %v vs %v", nodeBalanceWithP, pBalanceWithNode) } } } diff --git a/swap/swap.go b/swap/swap.go index 0a4278414b..f1cba0a793 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -173,7 +173,7 @@ func New(dbPath string, prvkey *ecdsa.PrivateKey, backendURL string, params *Par return nil, fmt.Errorf("initializing statestore: %w", err) } if params.DisconnectThreshold.Cmp(params.PaymentThreshold) < 1 { - return nil, fmt.Errorf("disconnect threshold lower or at payment threshold. DisconnectThreshold: %d, PaymentThreshold: %d", params.DisconnectThreshold, params.PaymentThreshold) + return nil, fmt.Errorf("disconnect threshold lower or at payment threshold. DisconnectThreshold: %v, PaymentThreshold: %v", params.DisconnectThreshold, params.PaymentThreshold) } // connect to the backend backend, err := ethclient.Dial(backendURL) @@ -321,7 +321,7 @@ func (s *Swap) modifyBalanceOk(amount *boundedint.Int256, swapPeer *Peer) (err e // check if balance with peer is over the disconnect threshold and if the message would increase the existing debt balance := swapPeer.getBalance() if balance.Cmp(s.params.DisconnectThreshold) >= 0 && amount.Cmp(boundedint.Int64ToInt256(0)) > 0 { - return fmt.Errorf("balance for peer %s is over the disconnect threshold %d and cannot incur more debt, disconnecting", swapPeer.ID().String(), s.params.DisconnectThreshold) + return fmt.Errorf("balance for peer %s is over the disconnect threshold %v and cannot incur more debt, disconnecting", swapPeer.ID().String(), s.params.DisconnectThreshold) } return nil diff --git a/swap/swap_test.go b/swap/swap_test.go index 64b33553fe..ee9f376a34 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -188,7 +188,7 @@ func comparePeerBalance(t *testing.T, s *Swap, peer enode.ID, expectedPeerBalanc t.Error("Unexpected peer balance retrieval failure.") } if !peerBalance.Equals(expectedPeerBalance) { - t.Errorf("Expected peer store balance to be %d, but is %d instead.", expectedPeerBalance, peerBalance) + t.Errorf("Expected peer store balance to be %v, but is %v instead.", expectedPeerBalance, peerBalance) } } @@ -667,7 +667,7 @@ func TestResetBalance(t *testing.T) { }) // the debitor should have already reset its balance if !creditor.getBalance().Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("unexpected balance to be 0, but it is %d", creditor.getBalance()) + t.Fatalf("unexpected balance to be 0, but it is %v", creditor.getBalance()) } // now load the cheque that the debitor created... @@ -696,7 +696,7 @@ func TestResetBalance(t *testing.T) { } // finally check that the creditor also successfully reset the balances if !debitor.getBalance().Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("unexpected balance to be 0, but it is %d", debitor.getBalance()) + t.Fatalf("unexpected balance to be 0, but it is %v", debitor.getBalance()) } } @@ -807,7 +807,7 @@ func TestRestoreBalanceFromStateStore(t *testing.T) { // compare the balances if !tmpBalance.Equals(newBalance) { - t.Fatalf("Unexpected balance value after sending cheap message test. Expected balance: %d, balance is: %d", tmpBalance, newBalance) + t.Fatalf("Unexpected balance value after sending cheap message test. Expected balance: %v, balance is: %v", tmpBalance, newBalance) } } From 904cfabd6cadedb967f92900dddad7863925cee0 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 6 Feb 2020 12:53:33 -0300 Subject: [PATCH 16/70] boundedint: change initial value for boundedints to 0 swap: fix calculateExpectedBalances & TestSwapRPC nil pointer bugs --- boundedint/int256.go | 2 +- boundedint/uint256.go | 2 +- swap/api_test.go | 14 +++++++++----- swap/protocol_test.go | 21 ++++++++++----------- swap/swap_test.go | 13 +++++++++---- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/boundedint/int256.go b/boundedint/int256.go index 9614c9168b..535a88f684 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -35,7 +35,7 @@ var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255) // NewInt256 creates a Int256 struct with a minimum initial underlying value func NewInt256() *Int256 { u := new(Int256) - u.value = *new(big.Int).Set(minInt256) + u.value = *new(big.Int).Set(big.NewInt(0)) return u } diff --git a/boundedint/uint256.go b/boundedint/uint256.go index 1f23a2ceaa..3e44dc016a 100644 --- a/boundedint/uint256.go +++ b/boundedint/uint256.go @@ -35,7 +35,7 @@ var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256 // NewUint256 creates a Uint256 struct with a minimum initial underlying value func NewUint256() *Uint256 { u := new(Uint256) - u.value = *new(big.Int).Set(minUint256) + u.value = *new(big.Int).Set(big.NewInt(0)) return u } diff --git a/swap/api_test.go b/swap/api_test.go index 570712dd34..94dbc80f86 100644 --- a/swap/api_test.go +++ b/swap/api_test.go @@ -113,31 +113,35 @@ func TestBalances(t *testing.T) { defer clean() // test balances are empty - testBalances(t, swap, map[enode.ID]int64{}) + testBalances(t, swap, map[enode.ID]*boundedint.Int256{}) // add peer testPeer := addPeer(t, swap) testPeerID := testPeer.ID() // test balances with one peer + balancePeer := boundedint.Int64ToInt256(808) setBalance(t, testPeer, boundedint.Int64ToInt256(808)) - testBalances(t, swap, map[enode.ID]int64{testPeerID: 808}) + testBalances(t, swap, map[enode.ID]*boundedint.Int256{testPeerID: balancePeer}) // add second peer testPeer2 := addPeer(t, swap) testPeer2ID := testPeer2.ID() // test balances with second peer + balancePeer2 := boundedint.Int64ToInt256(123) setBalance(t, testPeer2, boundedint.Int64ToInt256(123)) - testBalances(t, swap, map[enode.ID]int64{testPeerID: 808, testPeer2ID: 123}) + testBalances(t, swap, map[enode.ID]*boundedint.Int256{testPeerID: balancePeer, testPeer2ID: balancePeer2}) // test balances after balance change for peer + balancePeer = boundedint.Int64ToInt256(303) + balancePeer2 = boundedint.Int64ToInt256(123) setBalance(t, testPeer, boundedint.Int64ToInt256(303)) - testBalances(t, swap, map[enode.ID]int64{testPeerID: 303, testPeer2ID: 123}) + testBalances(t, swap, map[enode.ID]*boundedint.Int256{testPeerID: balancePeer, testPeer2ID: balancePeer2}) } // tests that a map of peerID:balance matches the result of the Balances function -func testBalances(t *testing.T, s *Swap, expectedBalances map[enode.ID]int64) { +func testBalances(t *testing.T, s *Swap, expectedBalances map[enode.ID]*boundedint.Int256) { t.Helper() actualBalances, err := s.Balances() if err != nil { diff --git a/swap/protocol_test.go b/swap/protocol_test.go index ed5f52eb9b..e97f0552fd 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -598,17 +598,17 @@ func TestSwapRPC(t *testing.T) { fakeBalance2 := boundedint.Int64ToInt256(-100) // query a first time, should give error - var balance *boundedint.Uint256 - err = rpcclient.Call(&balance, "swap_peerBalance", id1) + balance := boundedint.NewInt256() + err = rpcclient.Call(balance, "swap_peerBalance", id1) // at this point no balance should be there: no peer registered with Swap if err == nil { t.Fatal("Expected error but no error received") } log.Debug("servicenode balance", "balance", balance) - // ...thus balance should be zero - if !balance.Equals(boundedint.Int64ToInt256(0)) { - t.Fatalf("Expected balance to be 0 but it is %v", balance) + // ...thus balance should be empty + if !balance.Equals(boundedint.NewInt256()) { + t.Fatalf("Expected balance to be empty but it is %v", balance) } peer1, err := swap.addPeer(dummyPeer1.Peer, common.Address{}, common.Address{}) @@ -630,7 +630,7 @@ func TestSwapRPC(t *testing.T) { } // query them, values should coincide - err = rpcclient.Call(&balance, "swap_peerBalance", id1) + err = rpcclient.Call(balance, "swap_peerBalance", id1) if err != nil { t.Fatal(err) } @@ -639,7 +639,7 @@ func TestSwapRPC(t *testing.T) { t.Fatalf("Expected balance %v to be equal to fake balance %v, but it is not", balance, fakeBalance1) } - err = rpcclient.Call(&balance, "swap_peerBalance", id2) + err = rpcclient.Call(balance, "swap_peerBalance", id2) if err != nil { t.Fatal(err) } @@ -649,18 +649,17 @@ func TestSwapRPC(t *testing.T) { } // now call all balances - allBalances := make(map[enode.ID]int64) + allBalances := make(map[enode.ID]*boundedint.Int256) err = rpcclient.Call(&allBalances, "swap_balances") if err != nil { t.Fatal(err) } log.Debug("received balances", "allBalances", allBalances) - var s int64 + sum := boundedint.NewInt256() for _, v := range allBalances { - s += v + sum.Add(sum, v) } - sum := boundedint.Int64ToInt256(s) fakeSum, err := boundedint.NewInt256().Add(fakeBalance1, fakeBalance2) if err != nil { diff --git a/swap/swap_test.go b/swap/swap_test.go index ee9f376a34..3145ce3385 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -730,7 +730,7 @@ func addBookings(swap *Swap, bookings []booking) { // take a Swap struct and a list of bookings, and verify the resulting balances are as expected func verifyBookings(t *testing.T, s *Swap, bookings []booking) { t.Helper() - expectedBalances := calculateExpectedBalances(s, bookings) + expectedBalances := calculateExpectedBalances(t, s, bookings) realBalances, err := s.Balances() if err != nil { t.Fatal(err) @@ -752,15 +752,20 @@ func stringifyBalance(balance map[enode.ID]*boundedint.Int256) string { // take a swap struct and a list of bookings, and calculate the expected balances. // the result is a map which stores the balance for all the peers present in the bookings, // from the perspective of the node that loaded the Swap struct. -func calculateExpectedBalances(swap *Swap, bookings []booking) map[enode.ID]*boundedint.Int256 { +func calculateExpectedBalances(t *testing.T, swap *Swap, bookings []booking) map[enode.ID]*boundedint.Int256 { expectedBalances := make(map[enode.ID]*boundedint.Int256) for i := 0; i < len(bookings); i++ { booking := bookings[i] peerID := booking.peer.ID() - peerBalance := expectedBalances[peerID] + peerBalance, ok := expectedBalances[peerID] + if !ok { + peerBalance = boundedint.NewInt256() + } // peer balance should only be affected if debt is being reduced or if balance is smaller than disconnect threshold if peerBalance.Cmp(swap.params.DisconnectThreshold) < 0 || booking.amount.Cmp(boundedint.Int64ToInt256(0)) < 0 { - peerBalance.Add(peerBalance, booking.amount) + if _, err := peerBalance.Add(peerBalance, booking.amount); err != nil { + t.Fatal(err) + } } expectedBalances[peerID] = peerBalance } From 8a26add9e943a46fca912c59a007401a0bcaff5c Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 6 Feb 2020 14:56:13 -0300 Subject: [PATCH 17/70] main: update config tests for boundedint thresholds --- cmd/swarm/config_test.go | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index 28dd14177b..e8d452fa00 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -35,6 +35,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" "github.com/ethersphere/swarm" "github.com/ethersphere/swarm/api" + "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/swap" "github.com/ethersphere/swarm/testutil" ) @@ -227,6 +228,18 @@ func TestConfigCmdLineOverrides(t *testing.T) { t.Fatal(err) } + paymentThresholdOverride, err := boundedint.NewUint256().Add(&swap.DefaultPaymentThreshold, boundedint.Uint64ToUint256(1)) + if err != nil { + t.Fatal(err) + } + pt := paymentThresholdOverride.Value() + + disconnectThresholdOverride, err := boundedint.NewUint256().Add(&swap.DefaultDisconnectThreshold, boundedint.Uint64ToUint256(1)) + if err != nil { + t.Fatal(err) + } + dt := disconnectThresholdOverride.Value() + flags := []string{ fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "42", fmt.Sprintf("--%s", SwarmPortFlag.Name), httpPort, @@ -238,8 +251,8 @@ func TestConfigCmdLineOverrides(t *testing.T) { fmt.Sprintf("--%s", utils.DataDirFlag.Name), dir, fmt.Sprintf("--%s", utils.IPCPathFlag.Name), conf.IPCPath, "--verbosity", fmt.Sprintf("%d", *testutil.Loglevel), - fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), strconv.FormatUint(swap.DefaultPaymentThreshold+1, 10), - fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), strconv.FormatUint(swap.DefaultDisconnectThreshold+1, 10), + fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), strconv.FormatUint(pt.Uint64(), 10), + fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), strconv.FormatUint(dt.Uint64(), 10), fmt.Sprintf("--%s", SwarmEnablePinningFlag.Name), } @@ -287,12 +300,12 @@ func TestConfigCmdLineOverrides(t *testing.T) { t.Fatalf("Expected Cors flag to be set to %s, got %s", "*", info.Cors) } - if info.SwapPaymentThreshold != (swap.DefaultPaymentThreshold + 1) { - t.Fatalf("Expected SwapPaymentThreshold to be %d, but got %d", swap.DefaultPaymentThreshold+1, info.SwapPaymentThreshold) + if !info.SwapPaymentThreshold.Equals(paymentThresholdOverride) { + t.Fatalf("Expected SwapPaymentThreshold to be %v, but got %v", paymentThresholdOverride, info.SwapPaymentThreshold) } - if info.SwapDisconnectThreshold != (swap.DefaultDisconnectThreshold + 1) { - t.Fatalf("Expected SwapDisconnectThreshold to be %d, but got %d", swap.DefaultDisconnectThreshold+1, info.SwapDisconnectThreshold) + if !info.SwapDisconnectThreshold.Equals(disconnectThresholdOverride) { + t.Fatalf("Expected SwapDisconnectThreshold to be %v, but got %v", disconnectThresholdOverride, info.SwapDisconnectThreshold) } if info.EnablePinning != true { From e16b8f03a6898510d25ff65a75d13ebb01eb8c8a Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 6 Feb 2020 15:09:18 -0300 Subject: [PATCH 18/70] boundedint: change initial value for boundedints to 0 --- boundedint/int256.go | 4 ++-- boundedint/uint256.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/boundedint/int256.go b/boundedint/int256.go index 1894164ead..3ce179d133 100644 --- a/boundedint/int256.go +++ b/boundedint/int256.go @@ -32,10 +32,10 @@ type Int256 struct { var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)) // 2^255 - 1 -// NewInt256 creates a Int256 struct with a minimum initial underlying value +// NewInt256 creates a Int256 struct with an initial underlying value of zero func NewInt256() *Int256 { u := new(Int256) - u.value = *new(big.Int).Set(minInt256) + u.value = *new(big.Int).Set(big.NewInt(0)) return u } diff --git a/boundedint/uint256.go b/boundedint/uint256.go index d5f588bc33..0de8d96246 100644 --- a/boundedint/uint256.go +++ b/boundedint/uint256.go @@ -32,10 +32,10 @@ type Uint256 struct { var minUint256 = big.NewInt(0) var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)) // 2^256 - 1 -// NewUint256 creates a Uint256 struct with a minimum initial underlying value +// NewUint256 creates a Uint256 struct with an initial underlying value of zero func NewUint256() *Uint256 { u := new(Uint256) - u.value = *new(big.Int).Set(minUint256) + u.value = *new(big.Int).Set(big.NewInt(0)) return u } From 14bb3b355023add109a8420166ce373278ae150c Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 6 Feb 2020 16:54:26 -0300 Subject: [PATCH 19/70] boundedint: rename Uint256TestCase structure to BoundedIntTestCase --- boundedint/boundedint.go | 25 +++++++++++++++++++++++++ boundedint/uint256_test.go | 10 ++-------- 2 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 boundedint/boundedint.go diff --git a/boundedint/boundedint.go b/boundedint/boundedint.go new file mode 100644 index 0000000000..b651417656 --- /dev/null +++ b/boundedint/boundedint.go @@ -0,0 +1,25 @@ +// Copyright 2020 The Swarm Authors +// This file is part of the Swarm library. +// +// The Swarm library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Swarm library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the Swarm library. If not, see . + +package boundedint + +import "math/big" + +type BoundedIntTestCase struct { + name string + baseInteger *big.Int + expectsError bool +} diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 60e5adc5fc..0227f1a166 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -25,15 +25,9 @@ import ( "github.com/ethersphere/swarm/state" ) -type Uint256TestCase struct { - name string - baseInteger *big.Int - expectsError bool -} - // TestSet tests the creation of valid and invalid Uint256 structs by calling the Set function func TestSet(t *testing.T) { - testCases := []Uint256TestCase{ + testCases := []BoundedIntTestCase{ { name: "base 0", baseInteger: big.NewInt(0), @@ -91,7 +85,7 @@ func TestSet(t *testing.T) { testSet(t, testCases) } -func testSet(t *testing.T, testCases []Uint256TestCase) { +func testSet(t *testing.T, testCases []BoundedIntTestCase) { t.Helper() for _, tc := range testCases { From a6289279d490fa2e6a594425e19e54efa93db662 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 10:02:15 -0300 Subject: [PATCH 20/70] boundedint: add tests for Int256 type --- boundedint/int256_test.go | 176 +++++++++++++++++++++++++++++++++++++ boundedint/uint256_test.go | 10 +-- 2 files changed, 181 insertions(+), 5 deletions(-) create mode 100644 boundedint/int256_test.go diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go new file mode 100644 index 0000000000..15995a3b4a --- /dev/null +++ b/boundedint/int256_test.go @@ -0,0 +1,176 @@ +// Copyright 2020 The Swarm Authors +// This file is part of the Swarm library. +// +// The Swarm library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Swarm library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the Swarm library. If not, see . + +package boundedint + +import ( + "crypto/rand" + "io/ioutil" + "math/big" + "testing" + + "github.com/ethersphere/swarm/state" +) + +// TestSet tests the creation of valid and invalid Int256 structs by calling the Set function +func TestInt256Set(t *testing.T) { + testCases := []BoundedIntTestCase{ + { + name: "base 0", + baseInteger: big.NewInt(0), + expectsError: false, + }, + // negative numbers + { + name: "base -1", + baseInteger: big.NewInt(-1), + expectsError: false, + }, + { + name: "base -1 * 2^8", + baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), big.NewInt(-1)), + expectsError: false, + }, + { + name: "base -1 * 2^64", + baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil), big.NewInt(-1)), + expectsError: false, + }, + { + name: "base -1 * 2^256", + baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(-1)), + expectsError: true, + }, + { + name: "base -1 * 2^512", + baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(-1)), + expectsError: true, + }, + // positive numbers + { + name: "base 1", + baseInteger: big.NewInt(1), + expectsError: false, + }, + { + name: "base 2^8", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + expectsError: false, + }, + { + name: "base 2^128", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), + expectsError: false, + }, + { + name: "base 2^255 - 1", + baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), + expectsError: false, + }, + { + name: "base 2^255", + baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), + expectsError: true, + }, + { + name: "base 2^512", + baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(1)), + expectsError: true, + }, + } + + testInt256Set(t, testCases) +} + +func testInt256Set(t *testing.T, testCases []BoundedIntTestCase) { + t.Helper() + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result, err := NewInt256().Set(*tc.baseInteger) + if tc.expectsError && err == nil { + t.Fatalf("expected error when creating new Int256, but got none") + } + if !tc.expectsError { + if err != nil { + t.Fatalf("got unexpected error when creating new Int256: %v", err) + } + resultValue := result.Value() + if (&resultValue).Cmp(tc.baseInteger) != 0 { + t.Fatalf("expected value of %v, got %v instead", tc.baseInteger, result.value) + } + } + }) + } +} + +// TestCopy tests the duplication of an existing Int256 variable +func TestInt256Copy(t *testing.T) { + r, err := randomUint256() + if err != nil { + t.Fatal(err) + } + + c := NewUint256().Copy(r) + + if !c.Equals(r) { + t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) + } +} + +func randomInt256() (*Uint256, error) { + r, err := rand.Int(rand.Reader, new(big.Int).Sub(maxUint256, minUint256)) // base for random + if err != nil { + return nil, err + } + + randomUint256 := new(big.Int).Add(r, minUint256) // random is within [minInt256, maxInt256] + + return NewUint256().Set(*randomUint256) +} + +// TestStore indirectly tests the marshaling and unmarshaling of a random Int256 variable +func TestInt256Store(t *testing.T) { + testDir, err := ioutil.TempDir("", "uint256_test_store") + if err != nil { + t.Fatal(err) + } + + stateStore, err := state.NewDBStore(testDir) + defer stateStore.Close() + if err != nil { + t.Fatal(err) + } + + r, err := randomUint256() + if err != nil { + t.Fatal(err) + } + + k := r.String() + + stateStore.Put(k, r) + + var u *Uint256 + err = stateStore.Get(k, &u) + if err != nil { + t.Fatal(err) + } + + if !u.Equals(r) { + t.Fatalf("retrieved Uint256 %v has an unequal balance to the original Uint256 %v", u, r) + } +} diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 0227f1a166..91a5694595 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -26,7 +26,7 @@ import ( ) // TestSet tests the creation of valid and invalid Uint256 structs by calling the Set function -func TestSet(t *testing.T) { +func TestUint256Set(t *testing.T) { testCases := []BoundedIntTestCase{ { name: "base 0", @@ -82,10 +82,10 @@ func TestSet(t *testing.T) { }, } - testSet(t, testCases) + testUint256Set(t, testCases) } -func testSet(t *testing.T, testCases []BoundedIntTestCase) { +func testUint256Set(t *testing.T, testCases []BoundedIntTestCase) { t.Helper() for _, tc := range testCases { @@ -108,7 +108,7 @@ func testSet(t *testing.T, testCases []BoundedIntTestCase) { } // TestCopy tests the duplication of an existing Uint256 variable -func TestCopy(t *testing.T) { +func TestUint256Copy(t *testing.T) { r, err := randomUint256() if err != nil { t.Fatal(err) @@ -133,7 +133,7 @@ func randomUint256() (*Uint256, error) { } // TestStore indirectly tests the marshaling and unmarshaling of a random Uint256 variable -func TestStore(t *testing.T) { +func TestUint256Store(t *testing.T) { testDir, err := ioutil.TempDir("", "uint256_test_store") if err != nil { t.Fatal(err) From fbd16c6f39021d0d20ddbc092220694e0b47408f Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 12:07:09 -0300 Subject: [PATCH 21/70] boundedint: iterate Int256 tests --- boundedint/int256_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go index 15995a3b4a..00af41bfbd 100644 --- a/boundedint/int256_test.go +++ b/boundedint/int256_test.go @@ -119,32 +119,32 @@ func testInt256Set(t *testing.T, testCases []BoundedIntTestCase) { // TestCopy tests the duplication of an existing Int256 variable func TestInt256Copy(t *testing.T) { - r, err := randomUint256() + r, err := randomInt256() if err != nil { t.Fatal(err) } - c := NewUint256().Copy(r) + c := NewInt256().Copy(r) if !c.Equals(r) { - t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) + t.Fatalf("copy of Int256 %v has an unequal value of %v", r, c) } } -func randomInt256() (*Uint256, error) { - r, err := rand.Int(rand.Reader, new(big.Int).Sub(maxUint256, minUint256)) // base for random +func randomInt256() (*Int256, error) { + r, err := rand.Int(rand.Reader, new(big.Int).Sub(maxInt256, minInt256)) // base for random if err != nil { return nil, err } - randomUint256 := new(big.Int).Add(r, minUint256) // random is within [minInt256, maxInt256] + randomInt256 := new(big.Int).Add(r, minInt256) // random is within [minInt256, maxInt256] - return NewUint256().Set(*randomUint256) + return NewInt256().Set(*randomInt256) } // TestStore indirectly tests the marshaling and unmarshaling of a random Int256 variable func TestInt256Store(t *testing.T) { - testDir, err := ioutil.TempDir("", "uint256_test_store") + testDir, err := ioutil.TempDir("", "int256_test_store") if err != nil { t.Fatal(err) } @@ -171,6 +171,6 @@ func TestInt256Store(t *testing.T) { } if !u.Equals(r) { - t.Fatalf("retrieved Uint256 %v has an unequal balance to the original Uint256 %v", u, r) + t.Fatalf("retrieved Int256 %v has an unequal balance to the original Int256 %v", u, r) } } From d71e7c0819a3d2e6abe0b63cd8804be566dfd0b0 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 12:29:32 -0300 Subject: [PATCH 22/70] boundedint: iterate boundedint tests --- boundedint/int256_test.go | 11 ++++++++--- boundedint/uint256_test.go | 4 ++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go index 00af41bfbd..c291f91d27 100644 --- a/boundedint/int256_test.go +++ b/boundedint/int256_test.go @@ -50,13 +50,18 @@ func TestInt256Set(t *testing.T) { expectsError: false, }, { - name: "base -1 * 2^256", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(-1)), + name: "base -1 * 2^255", + baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(-1)), + expectsError: false, + }, + { + name: "base -1 * 2^255 - 1", + baseInteger: new(big.Int).Sub(new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(-1)), big.NewInt(1)), expectsError: true, }, { name: "base -1 * 2^512", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(-1)), expectsError: true, }, // positive numbers diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 91a5694595..869eab57c9 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -72,12 +72,12 @@ func TestUint256Set(t *testing.T) { }, { name: "base 2^256", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), expectsError: true, }, { name: "base 2^512", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(1)), + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, } From 264b9ad2e23a979552d011f6ea8e1afa06af17a4 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 12:38:53 -0300 Subject: [PATCH 23/70] swap: fix bug with wrong package name --- swap/swap_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/swap/swap_test.go b/swap/swap_test.go index a81ae1640d..06a5252fc0 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -698,11 +698,11 @@ func TestDebtCheques(t *testing.T) { defer cleanup() ctx := context.Background() - if err := testDeploy(ctx, creditorSwap, uint256.FromUint64(0)); err != nil { + if err := testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)); err != nil { t.Fatal(err) } - debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, uint256.FromUint64((DefaultPaymentThreshold * 2))) + debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, boundedint.Uint64ToUint256((DefaultPaymentThreshold * 2))) if err != nil { t.Fatal(err) } @@ -714,7 +714,7 @@ func TestDebtCheques(t *testing.T) { } // create debt cheque - chequeAmount := uint256.FromUint64(ChequeDebtTolerance * 2) + chequeAmount := boundedint.Uint64ToUint256(ChequeDebtTolerance * 2) cheque, err := newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) @@ -730,7 +730,7 @@ func TestDebtCheques(t *testing.T) { } // now create a (barely) admissible cheque - chequeAmount = uint256.FromUint64(ChequeDebtTolerance) + chequeAmount = boundedint.Uint64ToUint256(ChequeDebtTolerance) cheque, err = newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) From 0bd16a19500ed6655771c874638ef46f5d5c6001 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 15:05:21 -0300 Subject: [PATCH 24/70] boundedint: iterate boundedint tests --- boundedint/int256_test.go | 14 +++++++------- boundedint/uint256_test.go | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go index c291f91d27..bd31791698 100644 --- a/boundedint/int256_test.go +++ b/boundedint/int256_test.go @@ -41,27 +41,27 @@ func TestInt256Set(t *testing.T) { }, { name: "base -1 * 2^8", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: false, }, { name: "base -1 * 2^64", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: false, }, { name: "base -1 * 2^255", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), expectsError: false, }, { name: "base -1 * 2^255 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(-1)), big.NewInt(1)), + baseInteger: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), expectsError: true, }, { name: "base -1 * 2^512", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), expectsError: true, }, // positive numbers @@ -87,12 +87,12 @@ func TestInt256Set(t *testing.T) { }, { name: "base 2^255", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), expectsError: true, }, { name: "base 2^512", - baseInteger: new(big.Int).Add(new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), big.NewInt(1)), + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, } diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 869eab57c9..677289d03d 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -41,12 +41,12 @@ func TestUint256Set(t *testing.T) { }, { name: "base -1 * 2^8", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: true, }, { name: "base -1 * 2^64", - baseInteger: new(big.Int).Mul(new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil), big.NewInt(-1)), + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: true, }, // positive numbers From fff2c10b9612c8891d6b9c35ccd10d0237e76e88 Mon Sep 17 00:00:00 2001 From: mortelli Date: Fri, 7 Feb 2020 15:17:38 -0300 Subject: [PATCH 25/70] boundedint: iterate boundedint tests --- boundedint/int256_test.go | 216 ++++++++++++++++++------------------- boundedint/uint256_test.go | 183 +++++++++++++++---------------- 2 files changed, 192 insertions(+), 207 deletions(-) diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go index bd31791698..a4e390bfd1 100644 --- a/boundedint/int256_test.go +++ b/boundedint/int256_test.go @@ -17,93 +17,85 @@ package boundedint import ( - "crypto/rand" + "github.com/ethersphere/swarm/state" "io/ioutil" "math/big" "testing" - - "github.com/ethersphere/swarm/state" ) -// TestSet tests the creation of valid and invalid Int256 structs by calling the Set function -func TestInt256Set(t *testing.T) { - testCases := []BoundedIntTestCase{ - { - name: "base 0", - baseInteger: big.NewInt(0), - expectsError: false, - }, - // negative numbers - { - name: "base -1", - baseInteger: big.NewInt(-1), - expectsError: false, - }, - { - name: "base -1 * 2^8", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), - expectsError: false, - }, - { - name: "base -1 * 2^64", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), - expectsError: false, - }, - { - name: "base -1 * 2^255", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), - expectsError: false, - }, - { - name: "base -1 * 2^255 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), - expectsError: true, - }, - { - name: "base -1 * 2^512", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), - expectsError: true, - }, - // positive numbers - { - name: "base 1", - baseInteger: big.NewInt(1), - expectsError: false, - }, - { - name: "base 2^8", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), - expectsError: false, - }, - { - name: "base 2^128", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), - expectsError: false, - }, - { - name: "base 2^255 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), - expectsError: false, - }, - { - name: "base 2^255", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), - expectsError: true, - }, - { - name: "base 2^512", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), - expectsError: true, - }, - } - - testInt256Set(t, testCases) +var int256TestCases = []BoundedIntTestCase{ + { + name: "base 0", + baseInteger: big.NewInt(0), + expectsError: false, + }, + // negative numbers + { + name: "base -1", + baseInteger: big.NewInt(-1), + expectsError: false, + }, + { + name: "base -1 * 2^8", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + expectsError: false, + }, + { + name: "base -1 * 2^64", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), + expectsError: false, + }, + { + name: "base -1 * 2^255", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), + expectsError: false, + }, + { + name: "base -1 * 2^255 - 1", + baseInteger: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), + expectsError: true, + }, + { + name: "base -1 * 2^512", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), + expectsError: true, + }, + // positive numbers + { + name: "base 1", + baseInteger: big.NewInt(1), + expectsError: false, + }, + { + name: "base 2^8", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + expectsError: false, + }, + { + name: "base 2^128", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), + expectsError: false, + }, + { + name: "base 2^255 - 1", + baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), + expectsError: false, + }, + { + name: "base 2^255", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), + expectsError: true, + }, + { + name: "base 2^512", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), + expectsError: true, + }, } -func testInt256Set(t *testing.T, testCases []BoundedIntTestCase) { - t.Helper() - - for _, tc := range testCases { +// TestSet tests the creation of valid and invalid Int256 structs by calling the Set function +func TestInt256Set(t *testing.T) { + for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { result, err := NewInt256().Set(*tc.baseInteger) if tc.expectsError && err == nil { @@ -124,27 +116,21 @@ func testInt256Set(t *testing.T, testCases []BoundedIntTestCase) { // TestCopy tests the duplication of an existing Int256 variable func TestInt256Copy(t *testing.T) { - r, err := randomInt256() - if err != nil { - t.Fatal(err) - } - - c := NewInt256().Copy(r) - - if !c.Equals(r) { - t.Fatalf("copy of Int256 %v has an unequal value of %v", r, c) - } -} + for _, tc := range int256TestCases { + t.Run(tc.name, func(t *testing.T) { + if !tc.expectsError { + r, err := NewInt256().Set(*tc.baseInteger) + if err != nil { + t.Fatalf("got unexpected error when creating new Int256: %v", err) + } + c := NewInt256().Copy(r) -func randomInt256() (*Int256, error) { - r, err := rand.Int(rand.Reader, new(big.Int).Sub(maxInt256, minInt256)) // base for random - if err != nil { - return nil, err + if !c.Equals(r) { + t.Fatalf("copy of Int256 %v has an unequal value of %v", r, c) + } + } + }) } - - randomInt256 := new(big.Int).Add(r, minInt256) // random is within [minInt256, maxInt256] - - return NewInt256().Set(*randomInt256) } // TestStore indirectly tests the marshaling and unmarshaling of a random Int256 variable @@ -160,22 +146,28 @@ func TestInt256Store(t *testing.T) { t.Fatal(err) } - r, err := randomUint256() - if err != nil { - t.Fatal(err) - } + for _, tc := range int256TestCases { + t.Run(tc.name, func(t *testing.T) { + if !tc.expectsError { + r, err := NewInt256().Set(*tc.baseInteger) + if err != nil { + t.Fatalf("got unexpected error when creating new Int256: %v", err) + } - k := r.String() + k := r.String() - stateStore.Put(k, r) + stateStore.Put(k, r) - var u *Uint256 - err = stateStore.Get(k, &u) - if err != nil { - t.Fatal(err) - } + var u *Int256 + err = stateStore.Get(k, &u) + if err != nil { + t.Fatal(err) + } - if !u.Equals(r) { - t.Fatalf("retrieved Int256 %v has an unequal balance to the original Int256 %v", u, r) + if !u.Equals(r) { + t.Fatalf("retrieved Int256 %v has an unequal balance to the original Uint256 %v", u, r) + } + } + }) } } diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 677289d03d..108cbf1f82 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -17,7 +17,6 @@ package boundedint import ( - "crypto/rand" "io/ioutil" "math/big" "testing" @@ -25,70 +24,64 @@ import ( "github.com/ethersphere/swarm/state" ) -// TestSet tests the creation of valid and invalid Uint256 structs by calling the Set function -func TestUint256Set(t *testing.T) { - testCases := []BoundedIntTestCase{ - { - name: "base 0", - baseInteger: big.NewInt(0), - expectsError: false, - }, - // negative numbers - { - name: "base -1", - baseInteger: big.NewInt(-1), - expectsError: true, - }, - { - name: "base -1 * 2^8", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), - expectsError: true, - }, - { - name: "base -1 * 2^64", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), - expectsError: true, - }, - // positive numbers - { - name: "base 1", - baseInteger: big.NewInt(1), - expectsError: false, - }, - { - name: "base 2^8", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), - expectsError: false, - }, - { - name: "base 2^128", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), - expectsError: false, - }, - { - name: "base 2^256 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), - expectsError: false, - }, - { - name: "base 2^256", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), - expectsError: true, - }, - { - name: "base 2^512", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), - expectsError: true, - }, - } - - testUint256Set(t, testCases) +var uint256TestCases = []BoundedIntTestCase{ + { + name: "base 0", + baseInteger: big.NewInt(0), + expectsError: false, + }, + // negative numbers + { + name: "base -1", + baseInteger: big.NewInt(-1), + expectsError: true, + }, + { + name: "base -1 * 2^8", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + expectsError: true, + }, + { + name: "base -1 * 2^64", + baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), + expectsError: true, + }, + // positive numbers + { + name: "base 1", + baseInteger: big.NewInt(1), + expectsError: false, + }, + { + name: "base 2^8", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + expectsError: false, + }, + { + name: "base 2^128", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), + expectsError: false, + }, + { + name: "base 2^256 - 1", + baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), + expectsError: false, + }, + { + name: "base 2^256", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), + expectsError: true, + }, + { + name: "base 2^512", + baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), + expectsError: true, + }, } -func testUint256Set(t *testing.T, testCases []BoundedIntTestCase) { - t.Helper() - - for _, tc := range testCases { +// TestSet tests the creation of valid and invalid Uint256 structs by calling the Set function +func TestUint256Set(t *testing.T) { + for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { result, err := NewUint256().Set(*tc.baseInteger) if tc.expectsError && err == nil { @@ -109,27 +102,21 @@ func testUint256Set(t *testing.T, testCases []BoundedIntTestCase) { // TestCopy tests the duplication of an existing Uint256 variable func TestUint256Copy(t *testing.T) { - r, err := randomUint256() - if err != nil { - t.Fatal(err) - } - - c := NewUint256().Copy(r) - - if !c.Equals(r) { - t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) - } -} + for _, tc := range uint256TestCases { + t.Run(tc.name, func(t *testing.T) { + if !tc.expectsError { + r, err := NewUint256().Set(*tc.baseInteger) + if err != nil { + t.Fatalf("got unexpected error when creating new Uint256: %v", err) + } + c := NewUint256().Copy(r) -func randomUint256() (*Uint256, error) { - r, err := rand.Int(rand.Reader, new(big.Int).Sub(maxUint256, minUint256)) // base for random - if err != nil { - return nil, err + if !c.Equals(r) { + t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) + } + } + }) } - - randomUint256 := new(big.Int).Add(r, minUint256) // random is within [minUint256, maxUint256] - - return NewUint256().Set(*randomUint256) } // TestStore indirectly tests the marshaling and unmarshaling of a random Uint256 variable @@ -145,22 +132,28 @@ func TestUint256Store(t *testing.T) { t.Fatal(err) } - r, err := randomUint256() - if err != nil { - t.Fatal(err) - } + for _, tc := range uint256TestCases { + t.Run(tc.name, func(t *testing.T) { + if !tc.expectsError { + r, err := NewUint256().Set(*tc.baseInteger) + if err != nil { + t.Fatalf("got unexpected error when creating new Uint256: %v", err) + } - k := r.String() + k := r.String() - stateStore.Put(k, r) + stateStore.Put(k, r) - var u *Uint256 - err = stateStore.Get(k, &u) - if err != nil { - t.Fatal(err) - } + var u *Uint256 + err = stateStore.Get(k, &u) + if err != nil { + t.Fatal(err) + } - if !u.Equals(r) { - t.Fatalf("retrieved Uint256 %v has an unequal balance to the original Uint256 %v", u, r) + if !u.Equals(r) { + t.Fatalf("retrieved Uint256 %v has an unequal balance to the original Uint256 %v", u, r) + } + } + }) } } From 386fc6318521d0ed256d8455cf320c87e88f8e7c Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 10 Feb 2020 09:55:32 -0300 Subject: [PATCH 26/70] boundedint: fix linter errors --- boundedint/int256_test.go | 4 +++- boundedint/uint256_test.go | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/boundedint/int256_test.go b/boundedint/int256_test.go index a4e390bfd1..3ff93fb95b 100644 --- a/boundedint/int256_test.go +++ b/boundedint/int256_test.go @@ -17,10 +17,11 @@ package boundedint import ( - "github.com/ethersphere/swarm/state" "io/ioutil" "math/big" "testing" + + "github.com/ethersphere/swarm/state" ) var int256TestCases = []BoundedIntTestCase{ @@ -123,6 +124,7 @@ func TestInt256Copy(t *testing.T) { if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } + c := NewInt256().Copy(r) if !c.Equals(r) { diff --git a/boundedint/uint256_test.go b/boundedint/uint256_test.go index 108cbf1f82..84fd63296e 100644 --- a/boundedint/uint256_test.go +++ b/boundedint/uint256_test.go @@ -109,6 +109,7 @@ func TestUint256Copy(t *testing.T) { if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } + c := NewUint256().Copy(r) if !c.Equals(r) { From 6bff02e721ab05114a1f0930b51a19cfdd0c05ce Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 09:53:11 -0300 Subject: [PATCH 27/70] swap: fix import order --- contracts/swap/swap.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/swap/swap.go b/contracts/swap/swap.go index 9d3e16e07f..2e3257d177 100644 --- a/contracts/swap/swap.go +++ b/contracts/swap/swap.go @@ -27,8 +27,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" contract "github.com/ethersphere/go-sw3/contracts-v0-2-0/erc20simpleswap" - "github.com/ethersphere/swarm/swap/chain" "github.com/ethersphere/swarm/boundedint" + "github.com/ethersphere/swarm/swap/chain" ) // Contract interface defines the methods exported from the underlying go-bindings for the smart contract From 97fe6376e9c097e51a0944263689d7e6b424156c Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 11:20:57 -0300 Subject: [PATCH 28/70] swap: fix wrong backend import --- swap/common_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/common_test.go b/swap/common_test.go index bc392b4b62..3e126f9d83 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -233,7 +233,7 @@ func setupContractTest() func() { } // deploy for testing (needs simulated backend commit) -func testDeployWithPrivateKey(ctx context.Context, backend cswap.Backend, privateKey *ecdsa.PrivateKey, ownerAddress common.Address, depositAmount *boundedint.Uint256) (cswap.Contract, error) { +func testDeployWithPrivateKey(ctx context.Context, backend chain.Backend, privateKey *ecdsa.PrivateKey, ownerAddress common.Address, depositAmount *boundedint.Uint256) (cswap.Contract, error) { opts := bind.NewKeyedTransactor(privateKey) opts.Context = ctx From d59666e5adc4f4b8e354dedd5060a72cd6c915da Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 11:45:50 -0300 Subject: [PATCH 29/70] swap, boundedint: rename boundedint package to int256 --- contracts/swap/swap.go | 6 +-- swap/api.go | 8 ++-- swap/cashout.go | 14 +++--- swap/cashout_test.go | 14 +++--- swap/cheque.go | 6 +-- swap/common_test.go | 12 ++--- {boundedint => swap/int256}/boundedint.go | 2 +- {boundedint => swap/int256}/int256.go | 2 +- {boundedint => swap/int256}/int256_test.go | 2 +- {boundedint => swap/int256}/uint256.go | 2 +- {boundedint => swap/int256}/uint256_test.go | 2 +- swap/peer.go | 10 ++-- swap/protocol_test.go | 20 ++++---- swap/simulations_test.go | 8 ++-- swap/swap.go | 10 ++-- swap/swap_test.go | 52 ++++++++++----------- swap/types.go | 8 ++-- 17 files changed, 89 insertions(+), 89 deletions(-) rename {boundedint => swap/int256}/boundedint.go (97%) rename {boundedint => swap/int256}/int256.go (99%) rename {boundedint => swap/int256}/int256_test.go (99%) rename {boundedint => swap/int256}/uint256.go (99%) rename {boundedint => swap/int256}/uint256_test.go (99%) diff --git a/contracts/swap/swap.go b/contracts/swap/swap.go index 2e3257d177..8a096ba34a 100644 --- a/contracts/swap/swap.go +++ b/contracts/swap/swap.go @@ -27,8 +27,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" contract "github.com/ethersphere/go-sw3/contracts-v0-2-0/erc20simpleswap" - "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/swap/chain" + "github.com/ethersphere/swarm/swap/int256" ) // Contract interface defines the methods exported from the underlying go-bindings for the smart contract @@ -38,7 +38,7 @@ type Contract interface { // Deposit sends a raw transaction to the chequebook, triggering the fallback—depositing amount Deposit(auth *bind.TransactOpts, amout *big.Int) (*types.Receipt, error) // CashChequeBeneficiaryStart sends the transaction to cash a cheque as the beneficiary - CashChequeBeneficiaryStart(opts *bind.TransactOpts, beneficiary common.Address, cumulativePayout *boundedint.Uint256, ownerSig []byte) (*types.Transaction, error) + CashChequeBeneficiaryStart(opts *bind.TransactOpts, beneficiary common.Address, cumulativePayout *int256.Uint256, ownerSig []byte) (*types.Transaction, error) // CashChequeBeneficiaryResult processes the receipt from a CashChequeBeneficiary transaction CashChequeBeneficiaryResult(receipt *types.Receipt) *CashChequeResult // LiquidBalance returns the LiquidBalance (total balance in ERC20-token - total hard deposits in ERC20-token) of the chequebook @@ -131,7 +131,7 @@ func (s simpleContract) Deposit(auth *bind.TransactOpts, amount *big.Int) (*type } // CashChequeBeneficiaryStart sends the transaction to cash a cheque as the beneficiary -func (s simpleContract) CashChequeBeneficiaryStart(opts *bind.TransactOpts, beneficiary common.Address, cumulativePayout *boundedint.Uint256, ownerSig []byte) (*types.Transaction, error) { +func (s simpleContract) CashChequeBeneficiaryStart(opts *bind.TransactOpts, beneficiary common.Address, cumulativePayout *int256.Uint256, ownerSig []byte) (*types.Transaction, error) { payout := cumulativePayout.Value() // send a copy of cumulativePayout to instance as it modifies the supplied big int internally tx, err := s.instance.CashChequeBeneficiary(opts, beneficiary, big.NewInt(0).Set(&payout), ownerSig) diff --git a/swap/api.go b/swap/api.go index 1dc3ab9076..b1cfc8ae4a 100644 --- a/swap/api.go +++ b/swap/api.go @@ -7,9 +7,9 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" - "github.com/ethersphere/swarm/boundedint" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/state" + "github.com/ethersphere/swarm/swap/int256" ) // APIs is a node.Service interface method @@ -25,7 +25,7 @@ func (s *Swap) APIs() []rpc.API { } type swapAPI interface { - AvailableBalance() (*boundedint.Uint256, error) + AvailableBalance() (*int256.Uint256, error) PeerBalance(peer enode.ID) (int64, error) Balances() (map[enode.ID]int64, error) PeerCheques(peer enode.ID) (PeerCheques, error) @@ -54,7 +54,7 @@ func NewAPI(s *Swap) *API { } // AvailableBalance returns the total balance of the chequebook against which new cheques can be written -func (s *Swap) AvailableBalance() (*boundedint.Uint256, error) { +func (s *Swap) AvailableBalance() (*int256.Uint256, error) { // get the LiquidBalance of the chequebook contractLiquidBalance, err := s.contract.LiquidBalance(nil) if err != nil { @@ -91,7 +91,7 @@ func (s *Swap) AvailableBalance() (*boundedint.Uint256, error) { totalChequesWorth := new(big.Int).Sub(cashedChequesWorth, sentChequesWorth) tentativeLiquidBalance := new(big.Int).Add(contractLiquidBalance, totalChequesWorth) - return boundedint.NewUint256().Set(*tentativeLiquidBalance) + return int256.NewUint256().Set(*tentativeLiquidBalance) } // PeerBalance returns the balance for a given peer diff --git a/swap/cashout.go b/swap/cashout.go index a43bc7e4ff..3f7955e890 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -22,9 +22,9 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/metrics" - "github.com/ethersphere/swarm/boundedint" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/swap/chain" + "github.com/ethersphere/swarm/swap/int256" ) // CashChequeBeneficiaryTransactionCost is the expected gas cost of a CashChequeBeneficiary transaction @@ -81,7 +81,7 @@ func (c *CashoutProcessor) cashCheque(ctx context.Context, request *CashoutReque } // estimatePayout estimates the payout for a given cheque as well as the transaction cost -func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) (expectedPayout *boundedint.Uint256, transactionCosts *boundedint.Uint256, err error) { +func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) (expectedPayout *int256.Uint256, transactionCosts *int256.Uint256, err error) { otherSwap, err := contract.InstanceAt(cheque.Contract, c.backend) if err != nil { return nil, nil, err @@ -92,7 +92,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - paidOut, err := boundedint.NewUint256().Set(*po) + paidOut, err := int256.NewUint256().Set(*po) if err != nil { return nil, nil, err } @@ -102,21 +102,21 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - gasPrice, err := boundedint.NewUint256().Set(*gp) + gasPrice, err := int256.NewUint256().Set(*gp) if err != nil { return nil, nil, err } - transactionCosts, err = boundedint.NewUint256().Mul(gasPrice, boundedint.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) + transactionCosts, err = int256.NewUint256().Mul(gasPrice, int256.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) if err != nil { return nil, nil, err } if paidOut.Cmp(cheque.CumulativePayout) > 0 { - return boundedint.NewUint256(), transactionCosts, nil + return int256.NewUint256(), transactionCosts, nil } - expectedPayout, err = boundedint.NewUint256().Sub(cheque.CumulativePayout, paidOut) + expectedPayout, err = int256.NewUint256().Sub(cheque.CumulativePayout, paidOut) if err != nil { return nil, nil, err } diff --git a/swap/cashout_test.go b/swap/cashout_test.go index ace3fb6ddf..f0da97e40a 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -23,7 +23,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/log" "github.com/ethersphere/swarm/swap/chain" - "github.com/ethersphere/swarm/boundedint" + "github.com/ethersphere/swarm/swap/int256" ) // TestContractIntegration tests a end-to-end cheque interaction. @@ -36,7 +36,7 @@ func TestContractIntegration(t *testing.T) { reset := setupContractTest() defer reset() - payout := boundedint.Uint64ToUint256(42) + payout := int256.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -73,7 +73,7 @@ func TestContractIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - paidOut, err := boundedint.NewUint256().Set(*result) + paidOut, err := int256.NewUint256().Set(*result) if err != nil { t.Fatal(err) } @@ -84,7 +84,7 @@ func TestContractIntegration(t *testing.T) { log.Debug("cheques result", "result", result) // create a cheque that will bounce - _, err = payout.Add(payout, boundedint.Uint64ToUint256(10000*RetrieveRequestPrice)) + _, err = payout.Add(payout, int256.Uint64ToUint256(10000*RetrieveRequestPrice)) if err != nil { t.Fatal(err) } @@ -121,7 +121,7 @@ func TestCashCheque(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := boundedint.Uint64ToUint256(42) + payout := int256.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -159,7 +159,7 @@ func TestEstimatePayout(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := boundedint.Uint64ToUint256(42) + payout := int256.Uint64ToUint256(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -181,7 +181,7 @@ func TestEstimatePayout(t *testing.T) { } // the gas price in the simulated backend is 1 therefore the total transactionCost should be 50000 * 1 = 50000 - if !transactionCost.Equals(boundedint.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) { + if !transactionCost.Equals(int256.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) { t.Fatalf("unexpected transaction cost: got %v, wanted: %d", transactionCost, 0) } } diff --git a/swap/cheque.go b/swap/cheque.go index 857b195c3d..9d7ccfc4e8 100644 --- a/swap/cheque.go +++ b/swap/cheque.go @@ -23,7 +23,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethersphere/swarm/boundedint" + "github.com/ethersphere/swarm/swap/int256" ) // encodeForSignature encodes the cheque params in the format used in the signing procedure @@ -133,8 +133,8 @@ func (cheque *Cheque) verifyChequeProperties(p *Peer, expectedBeneficiary common // verifyChequeAgainstLast verifies that the amount is higher than in the previous cheque and the increase is as expected // returns the actual amount received in this cheque -func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *boundedint.Uint256) (*boundedint.Uint256, error) { - actualAmount := boundedint.NewUint256().Copy(cheque.CumulativePayout) +func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *int256.Uint256) (*int256.Uint256, error) { + actualAmount := int256.NewUint256().Copy(cheque.CumulativePayout) if lastCheque != nil { if cheque.CumulativePayout.Cmp(lastCheque.CumulativePayout) < 1 { diff --git a/swap/common_test.go b/swap/common_test.go index 3e126f9d83..1be1a68bae 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -19,13 +19,13 @@ import ( "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/simulations/adapters" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" - "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" "github.com/ethersphere/swarm/swap/chain" mock "github.com/ethersphere/swarm/swap/chain/mock" + "github.com/ethersphere/swarm/swap/int256" ) // swapTestBackend encapsulates the SimulatedBackend and can offer @@ -162,7 +162,7 @@ func newTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: boundedint.Uint64ToUint256(42), + CumulativePayout: int256.Uint64ToUint256(42), Beneficiary: beneficiaryAddress, }, Honey: uint64(42), @@ -171,7 +171,7 @@ func newTestCheque() *Cheque { return cheque } -func newSignedTestCheque(testChequeContract common.Address, beneficiaryAddress common.Address, cumulativePayout *boundedint.Uint256, signingKey *ecdsa.PrivateKey) (*Cheque, error) { +func newSignedTestCheque(testChequeContract common.Address, beneficiaryAddress common.Address, cumulativePayout *int256.Uint256, signingKey *ecdsa.PrivateKey) (*Cheque, error) { cp := cumulativePayout.Value() cheque := &Cheque{ ChequeParams: ChequeParams{ @@ -197,7 +197,7 @@ func newRandomTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: boundedint.Uint64ToUint256(amount), + CumulativePayout: int256.Uint64ToUint256(amount), Beneficiary: beneficiaryAddress, }, Honey: amount, @@ -233,7 +233,7 @@ func setupContractTest() func() { } // deploy for testing (needs simulated backend commit) -func testDeployWithPrivateKey(ctx context.Context, backend chain.Backend, privateKey *ecdsa.PrivateKey, ownerAddress common.Address, depositAmount *boundedint.Uint256) (cswap.Contract, error) { +func testDeployWithPrivateKey(ctx context.Context, backend chain.Backend, privateKey *ecdsa.PrivateKey, ownerAddress common.Address, depositAmount *int256.Uint256) (cswap.Contract, error) { opts := bind.NewKeyedTransactor(privateKey) opts.Context = ctx @@ -281,7 +281,7 @@ func testDeployWithPrivateKey(ctx context.Context, backend chain.Backend, privat } // deploy for testing (needs simulated backend commit) -func testDeploy(ctx context.Context, swap *Swap, depositAmount *boundedint.Uint256) (err error) { +func testDeploy(ctx context.Context, swap *Swap, depositAmount *int256.Uint256) (err error) { swap.contract, err = testDeployWithPrivateKey(ctx, swap.backend, swap.owner.privateKey, swap.owner.address, depositAmount) return err } diff --git a/boundedint/boundedint.go b/swap/int256/boundedint.go similarity index 97% rename from boundedint/boundedint.go rename to swap/int256/boundedint.go index b651417656..65813e02a8 100644 --- a/boundedint/boundedint.go +++ b/swap/int256/boundedint.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package boundedint +package int256 import "math/big" diff --git a/boundedint/int256.go b/swap/int256/int256.go similarity index 99% rename from boundedint/int256.go rename to swap/int256/int256.go index 3ce179d133..1d8abf19e3 100644 --- a/boundedint/int256.go +++ b/swap/int256/int256.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package boundedint +package int256 import ( "fmt" diff --git a/boundedint/int256_test.go b/swap/int256/int256_test.go similarity index 99% rename from boundedint/int256_test.go rename to swap/int256/int256_test.go index 3ff93fb95b..13ec24ca22 100644 --- a/boundedint/int256_test.go +++ b/swap/int256/int256_test.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package boundedint +package int256 import ( "io/ioutil" diff --git a/boundedint/uint256.go b/swap/int256/uint256.go similarity index 99% rename from boundedint/uint256.go rename to swap/int256/uint256.go index 0de8d96246..7d02714a83 100644 --- a/boundedint/uint256.go +++ b/swap/int256/uint256.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package boundedint +package int256 import ( "fmt" diff --git a/boundedint/uint256_test.go b/swap/int256/uint256_test.go similarity index 99% rename from boundedint/uint256_test.go rename to swap/int256/uint256_test.go index 84fd63296e..76d7ca73b0 100644 --- a/boundedint/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see . -package boundedint +package int256 import ( "io/ioutil" diff --git a/swap/peer.go b/swap/peer.go index d09bab1e4a..1cdd12537d 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -26,8 +26,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" - "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/p2p/protocols" + "github.com/ethersphere/swarm/swap/int256" ) // ErrDontOwe indictates that no balance is actially owned @@ -117,12 +117,12 @@ func (p *Peer) setPendingCheque(cheque *Cheque) error { // getLastSentCumulativePayout returns the cumulative payout of the last sent cheque or 0 if there is none // the caller is expected to hold p.lock -func (p *Peer) getLastSentCumulativePayout() *boundedint.Uint256 { +func (p *Peer) getLastSentCumulativePayout() *int256.Uint256 { lastCheque := p.getLastSentCheque() if lastCheque != nil { return lastCheque.CumulativePayout } - return boundedint.NewUint256() + return int256.NewUint256() } // the caller is expected to hold p.lock @@ -167,10 +167,10 @@ func (p *Peer) createCheque() (*Cheque, error) { if err != nil { return nil, fmt.Errorf("error getting price from oracle: %v", err) } - price := boundedint.Uint64ToUint256(oraclePrice) + price := int256.Uint64ToUint256(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() - newCumulativePayout, err := boundedint.NewUint256().Add(cumulativePayout, price) + newCumulativePayout, err := int256.NewUint256().Add(cumulativePayout, price) if err != nil { return nil, err } diff --git a/swap/protocol_test.go b/swap/protocol_test.go index bbb8db5917..34af07b0a3 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -32,9 +32,9 @@ import ( "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" - "github.com/ethersphere/swarm/boundedint" contract "github.com/ethersphere/swarm/contracts/swap" p2ptest "github.com/ethersphere/swarm/p2p/testing" + "github.com/ethersphere/swarm/swap/int256" colorable "github.com/mattn/go-colorable" ) @@ -50,7 +50,7 @@ type swapTester struct { } // creates a new protocol tester for swap with a deployed chequebook -func newSwapTester(t *testing.T, backend *swapTestBackend, depositAmount *boundedint.Uint256) (*swapTester, func(), error) { +func newSwapTester(t *testing.T, backend *swapTestBackend, depositAmount *int256.Uint256) (*swapTester, func(), error) { swap, clean := newTestSwap(t, ownerKey, backend) err := testDeploy(context.Background(), swap, depositAmount) @@ -135,7 +135,7 @@ func correctSwapHandshakeMsg(swap *Swap) *HandshakeMsg { // TestHandshake tests the correct handshake scenario func TestHandshake(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -153,7 +153,7 @@ func TestHandshake(t *testing.T) { // TestHandshakeInvalidChainID tests that a handshake with the wrong chain id is rejected func TestHandshakeInvalidChainID(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -175,7 +175,7 @@ func TestHandshakeInvalidChainID(t *testing.T) { // TestHandshakeEmptyContract tests that a handshake with an empty contract address is rejected func TestHandshakeEmptyContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -197,7 +197,7 @@ func TestHandshakeEmptyContract(t *testing.T) { // TestHandshakeInvalidContract tests that a handshake with an address that's not a valid chequebook func TestHandshakeInvalidContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, boundedint.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -223,7 +223,7 @@ func TestHandshakeInvalidContract(t *testing.T) { func TestEmitCheque(t *testing.T) { testBackend := newTestBackend(t) - protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint64ToUint256(0)) defer clean() if err != nil { t.Fatal(err) @@ -243,7 +243,7 @@ func TestEmitCheque(t *testing.T) { // gasPrice on testBackend == 1 // estimated gas costs == 50000 // cheque should be sent if the accumulated amount of uncashed cheques is worth more than 100000 - balance := boundedint.Uint64ToUint256(100001) + balance := int256.Uint64ToUint256(100001) balanceValue := balance.Value() if err := testDeploy(context.Background(), debitorSwap, balance); err != nil { @@ -331,7 +331,7 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - protocolTester, clean, err := newSwapTester(t, testBackend, boundedint.Uint64ToUint256(DefaultPaymentThreshold*2)) + protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint64ToUint256(DefaultPaymentThreshold*2)) defer clean() if err != nil { t.Fatal(err) @@ -381,7 +381,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal("Expected pending cheque") } - if !pending.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedAmount)) { + if !pending.CumulativePayout.Equals(int256.Uint64ToUint256(expectedAmount)) { t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index 44aec2c9ed..e3b8be9e70 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -43,12 +43,12 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/rpc" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" - "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network/simulation" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" mock "github.com/ethersphere/swarm/swap/chain/mock" + "github.com/ethersphere/swarm/swap/int256" ) /* @@ -161,7 +161,7 @@ func newSimServiceMap(params *swapSimulationParams) map[string]simulation.Servic ts.spec.Hook = protocols.NewAccounting(balance) ts.swap = balance // deploy the accounting to the `SimulatedBackend` - err = testDeploy(context.Background(), balance, boundedint.Uint64ToUint256(100000*RetrieveRequestPrice)) + err = testDeploy(context.Background(), balance, int256.Uint64ToUint256(100000*RetrieveRequestPrice)) if err != nil { return nil, nil, err } @@ -427,7 +427,7 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatalf("Expected symmetric cheques payout, but they are not: %v vs %v", cheque1.CumulativePayout, cheque2.CumulativePayout) } - if !cheque2.CumulativePayout.Equals(boundedint.Uint64ToUint256(expectedPayout)) { + if !cheque2.CumulativePayout.Equals(int256.Uint64ToUint256(expectedPayout)) { t.Fatalf("Expected %d in cumulative payout, got %v", expectedPayout, cheque1.CumulativePayout) } @@ -663,7 +663,7 @@ func waitForChequeProcessed(t *testing.T, backend *swapTestBackend, counter metr p.lock.Lock() lastPayout := p.getLastSentCumulativePayout() p.lock.Unlock() - if !lastPayout.Equals(boundedint.Uint64ToUint256(expectedLastPayout)) { + if !lastPayout.Equals(int256.Uint64ToUint256(expectedLastPayout)) { time.Sleep(5 * time.Millisecond) continue } else { diff --git a/swap/swap.go b/swap/swap.go index 20618a2022..3a3333738a 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -34,13 +34,13 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/p2p/enode" - "github.com/ethersphere/swarm/boundedint" "github.com/ethersphere/swarm/contracts/swap" contract "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" "github.com/ethersphere/swarm/swap/chain" + "github.com/ethersphere/swarm/swap/int256" ) // ErrInvalidChequeSignature indicates the signature on the cheque was invalid @@ -440,8 +440,8 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque return protocols.Break(err) } - costsMultiplier := boundedint.Uint64ToUint256(2) - costThreshold, err := boundedint.NewUint256().Mul(transactionCosts, costsMultiplier) + costsMultiplier := int256.Uint64ToUint256(2) + costThreshold, err := int256.NewUint256().Mul(transactionCosts, costsMultiplier) if err != nil { return err } @@ -506,7 +506,7 @@ func cashCheque(s *Swap, cheque *Cheque) { // processAndVerifyCheque verifies the cheque and compares it with the last received cheque // if the cheque is valid it will also be saved as the new last cheque // the caller is expected to hold p.lock -func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*boundedint.Uint256, error) { +func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, error) { if err := cheque.verifyChequeProperties(p, s.owner.address); err != nil { return nil, err } @@ -519,7 +519,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*boundedint.Uint return nil, err } - actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, boundedint.Uint64ToUint256(expectedAmount)) + actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, int256.Uint64ToUint256(expectedAmount)) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index 588f1576d3..38d3f61453 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -44,10 +44,10 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" contractFactory "github.com/ethersphere/go-sw3/contracts-v0-2-0/simpleswapfactory" - "github.com/ethersphere/swarm/boundedint" cswap "github.com/ethersphere/swarm/contracts/swap" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/state" + "github.com/ethersphere/swarm/swap/int256" "github.com/ethersphere/swarm/testutil" ) @@ -434,7 +434,7 @@ func TestStartChequebookFailure(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, config.testBackend) defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -493,7 +493,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -519,7 +519,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -551,7 +551,7 @@ func TestStartChequebookSuccess(t *testing.T) { func TestDisconnectThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, boundedint.Uint64ToUint256(0)) + testDeploy(context.Background(), swap, int256.Uint64ToUint256(0)) testPeer := newDummyPeer() swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) @@ -577,7 +577,7 @@ func TestDisconnectThreshold(t *testing.T) { func TestPaymentThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, boundedint.Uint64ToUint256(DefaultPaymentThreshold)) + testDeploy(context.Background(), swap, int256.Uint64ToUint256(DefaultPaymentThreshold)) testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) if err := swap.Add(-int64(DefaultPaymentThreshold), testPeer.Peer); err != nil { @@ -586,7 +586,7 @@ func TestPaymentThreshold(t *testing.T) { var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(boundedint.Uint64ToUint256(DefaultPaymentThreshold)) { + if !cheque.CumulativePayout.Equals(int256.Uint64ToUint256(DefaultPaymentThreshold)) { t.Fatal() } } @@ -610,11 +610,11 @@ func TestResetBalance(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err := testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)) + err := testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, boundedint.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, debitorSwap, int256.Uint64ToUint256(testAmount)) if err != nil { t.Fatal(err) } @@ -699,11 +699,11 @@ func TestDebtCheques(t *testing.T) { defer cleanup() ctx := context.Background() - if err := testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(0)); err != nil { + if err := testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(0)); err != nil { t.Fatal(err) } - debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, boundedint.Uint64ToUint256((DefaultPaymentThreshold * 2))) + debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, int256.Uint64ToUint256((DefaultPaymentThreshold * 2))) if err != nil { t.Fatal(err) } @@ -715,7 +715,7 @@ func TestDebtCheques(t *testing.T) { } // create debt cheque - chequeAmount := boundedint.Uint64ToUint256(ChequeDebtTolerance * 2) + chequeAmount := int256.Uint64ToUint256(ChequeDebtTolerance * 2) cheque, err := newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) @@ -731,7 +731,7 @@ func TestDebtCheques(t *testing.T) { } // now create a (barely) admissible cheque - chequeAmount = boundedint.Uint64ToUint256(ChequeDebtTolerance) + chequeAmount = int256.Uint64ToUint256(ChequeDebtTolerance) cheque, err = newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) @@ -964,7 +964,7 @@ func TestVerifyContract(t *testing.T) { defer clean() // deploy a new swap contract - err := testDeploy(context.TODO(), swap, boundedint.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) if err != nil { t.Fatalf("Error in deploy: %v", err) } @@ -1102,7 +1102,7 @@ func TestPeerVerifyChequePropertiesInvalidCheque(t *testing.T) { // TestPeerVerifyChequeAgainstLast tests that verifyChequeAgainstLast accepts a cheque with higher amount func TestPeerVerifyChequeAgainstLast(t *testing.T) { - increase := boundedint.Uint64ToUint256(10) + increase := int256.Uint64ToUint256(10) oldCheque := newTestCheque() newCheque := newTestCheque() @@ -1123,7 +1123,7 @@ func TestPeerVerifyChequeAgainstLast(t *testing.T) { // TestPeerVerifyChequeAgainstLastInvalid tests that verifyChequeAgainstLast rejects cheques with lower amount or an unexpected value func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { - increase := boundedint.Uint64ToUint256(10) + increase := int256.Uint64ToUint256(10) // cheque with same or lower amount oldCheque := newTestCheque() @@ -1136,7 +1136,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := boundedint.NewUint256().Add(increase, boundedint.Uint64ToUint256(5)) + cumulativePayoutIncrease, err := int256.NewUint256().Add(increase, int256.Uint64ToUint256(5)) if err != nil { t.Fatal(err) } @@ -1176,7 +1176,7 @@ func TestPeerProcessAndVerifyCheque(t *testing.T) { // create another cheque with higher amount otherCheque := newTestCheque() - _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, boundedint.Uint64ToUint256(10)) + _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, int256.Uint64ToUint256(10)) if err != nil { t.Fatal(err) } @@ -1224,7 +1224,7 @@ func TestPeerProcessAndVerifyChequeInvalid(t *testing.T) { // invalid cheque because amount is lower otherCheque := newTestCheque() - _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, boundedint.Uint64ToUint256(10)) + _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, int256.Uint64ToUint256(10)) if err != nil { t.Fatal(err) } @@ -1272,11 +1272,11 @@ func TestSwapLogToFile(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err = testDeploy(ctx, creditorSwap, boundedint.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(testAmount)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, boundedint.Uint64ToUint256(0)) + err = testDeploy(ctx, debitorSwap, int256.Uint64ToUint256(0)) if err != nil { t.Fatal(err) } @@ -1341,7 +1341,7 @@ func TestPeerGetLastSentCumulativePayout(t *testing.T) { _, peer, clean := newTestSwapAndPeer(t, ownerKey) defer clean() - if !peer.getLastSentCumulativePayout().Equals(boundedint.Uint64ToUint256(0)) { + if !peer.getLastSentCumulativePayout().Equals(int256.Uint64ToUint256(0)) { t.Fatalf("last cumulative payout should be 0 in the beginning, was %v", peer.getLastSentCumulativePayout()) } @@ -1363,7 +1363,7 @@ func TestAvailableBalance(t *testing.T) { cleanup := setupContractTest() defer cleanup() - depositAmount := boundedint.Uint64ToUint256(9000 * RetrieveRequestPrice) + depositAmount := int256.Uint64ToUint256(9000 * RetrieveRequestPrice) // deploy a chequebook err := testDeploy(context.TODO(), swap, depositAmount) @@ -1385,8 +1385,8 @@ func TestAvailableBalance(t *testing.T) { t.Fatalf("available balance not equal to deposited amount. available balance: %v, deposit amount: %v", availableBalance, depositAmount) } // withdraw 50 - withdrawAmount := boundedint.Uint64ToUint256(50) - netDeposit, err := boundedint.NewUint256().Sub(depositAmount, withdrawAmount) + withdrawAmount := int256.Uint64ToUint256(50) + netDeposit, err := int256.NewUint256().Sub(depositAmount, withdrawAmount) if err != nil { t.Fatal(err) } @@ -1426,7 +1426,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatal(err) } // verify available balance - expectedBalance, err := boundedint.NewUint256().Sub(netDeposit, boundedint.Uint64ToUint256(chequeAmount)) + expectedBalance, err := int256.NewUint256().Sub(netDeposit, int256.Uint64ToUint256(chequeAmount)) if err != nil { t.Fatal(err) } diff --git a/swap/types.go b/swap/types.go index 37dc82feaa..c9d1735cc3 100644 --- a/swap/types.go +++ b/swap/types.go @@ -18,14 +18,14 @@ package swap import ( "github.com/ethereum/go-ethereum/common" - "github.com/ethersphere/swarm/boundedint" + "github.com/ethersphere/swarm/swap/int256" ) // ChequeParams encapsulate all cheque parameters type ChequeParams struct { - Contract common.Address // address of chequebook, needed to avoid cross-contract submission - Beneficiary common.Address // address of the beneficiary, the contract which will redeem the cheque - CumulativePayout *boundedint.Uint256 // cumulative amount of the cheque in currency + Contract common.Address // address of chequebook, needed to avoid cross-contract submission + Beneficiary common.Address // address of the beneficiary, the contract which will redeem the cheque + CumulativePayout *int256.Uint256 // cumulative amount of the cheque in currency } // Cheque encapsulates the parameters and the signature From ed4af97549798dde071724c631afd43d970dc921 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 11:52:14 -0300 Subject: [PATCH 30/70] int256: rename test case struct --- swap/int256/boundedint.go | 25 ------------------------- swap/int256/int256_test.go | 8 +++++++- swap/int256/uint256_test.go | 2 +- 3 files changed, 8 insertions(+), 27 deletions(-) delete mode 100644 swap/int256/boundedint.go diff --git a/swap/int256/boundedint.go b/swap/int256/boundedint.go deleted file mode 100644 index 65813e02a8..0000000000 --- a/swap/int256/boundedint.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2020 The Swarm Authors -// This file is part of the Swarm library. -// -// The Swarm library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The Swarm library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the Swarm library. If not, see . - -package int256 - -import "math/big" - -type BoundedIntTestCase struct { - name string - baseInteger *big.Int - expectsError bool -} diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 13ec24ca22..3cf3dbae1e 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -24,7 +24,13 @@ import ( "github.com/ethersphere/swarm/state" ) -var int256TestCases = []BoundedIntTestCase{ +type testCase struct { + name string + baseInteger *big.Int + expectsError bool +} + +var int256TestCases = []testCase{ { name: "base 0", baseInteger: big.NewInt(0), diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 76d7ca73b0..1aea0544ff 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -24,7 +24,7 @@ import ( "github.com/ethersphere/swarm/state" ) -var uint256TestCases = []BoundedIntTestCase{ +var uint256TestCases = []testCase{ { name: "base 0", baseInteger: big.NewInt(0), From b7f9ed7316d2f2e30c8dd98a70e6674e47381978 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 15:42:51 -0300 Subject: [PATCH 31/70] int256: rename Uint64ToUint256 func to Uint256From, add Int256From function, iterate TestInt256Copy and TestUint256Copy funcs --- swap/cashout.go | 2 +- swap/cashout_test.go | 10 ++++---- swap/common_test.go | 4 ++-- swap/int256/int256.go | 8 +++++++ swap/int256/int256_test.go | 33 +++++++++++++++---------- swap/int256/uint256.go | 4 ++-- swap/int256/uint256_test.go | 33 +++++++++++++++---------- swap/peer.go | 2 +- swap/protocol_test.go | 16 ++++++------- swap/simulations_test.go | 6 ++--- swap/swap.go | 4 ++-- swap/swap_test.go | 48 ++++++++++++++++++------------------- 12 files changed, 96 insertions(+), 74 deletions(-) diff --git a/swap/cashout.go b/swap/cashout.go index 3f7955e890..2946a55a12 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -107,7 +107,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - transactionCosts, err = int256.NewUint256().Mul(gasPrice, int256.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) + transactionCosts, err = int256.NewUint256().Mul(gasPrice, int256.Uint256From(CashChequeBeneficiaryTransactionCost)) if err != nil { return nil, nil, err } diff --git a/swap/cashout_test.go b/swap/cashout_test.go index f0da97e40a..82db6ff328 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -36,7 +36,7 @@ func TestContractIntegration(t *testing.T) { reset := setupContractTest() defer reset() - payout := int256.Uint64ToUint256(42) + payout := int256.Uint256From(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -84,7 +84,7 @@ func TestContractIntegration(t *testing.T) { log.Debug("cheques result", "result", result) // create a cheque that will bounce - _, err = payout.Add(payout, int256.Uint64ToUint256(10000*RetrieveRequestPrice)) + _, err = payout.Add(payout, int256.Uint256From(10000*RetrieveRequestPrice)) if err != nil { t.Fatal(err) } @@ -121,7 +121,7 @@ func TestCashCheque(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := int256.Uint64ToUint256(42) + payout := int256.Uint256From(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -159,7 +159,7 @@ func TestEstimatePayout(t *testing.T) { defer reset() cashoutProcessor := newCashoutProcessor(backend, ownerKey) - payout := int256.Uint64ToUint256(42) + payout := int256.Uint256From(42) chequebook, err := testDeployWithPrivateKey(context.Background(), backend, ownerKey, ownerAddress, payout) if err != nil { @@ -181,7 +181,7 @@ func TestEstimatePayout(t *testing.T) { } // the gas price in the simulated backend is 1 therefore the total transactionCost should be 50000 * 1 = 50000 - if !transactionCost.Equals(int256.Uint64ToUint256(CashChequeBeneficiaryTransactionCost)) { + if !transactionCost.Equals(int256.Uint256From(CashChequeBeneficiaryTransactionCost)) { t.Fatalf("unexpected transaction cost: got %v, wanted: %d", transactionCost, 0) } } diff --git a/swap/common_test.go b/swap/common_test.go index 1be1a68bae..af1e73f4b7 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -162,7 +162,7 @@ func newTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: int256.Uint64ToUint256(42), + CumulativePayout: int256.Uint256From(42), Beneficiary: beneficiaryAddress, }, Honey: uint64(42), @@ -197,7 +197,7 @@ func newRandomTestCheque() *Cheque { cheque := &Cheque{ ChequeParams: ChequeParams{ Contract: testChequeContract, - CumulativePayout: int256.Uint64ToUint256(amount), + CumulativePayout: int256.Uint256From(amount), Beneficiary: beneficiaryAddress, }, Honey: amount, diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 1d8abf19e3..39a861474f 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -44,6 +44,14 @@ func (u *Int256) Value() big.Int { return u.value } +// Int256From creates a Int256 struct based on the given int64 param +// any int64 is valid as a Int256 +func Int256From(base int64) *Int256 { + u := NewInt256() + u.value = *new(big.Int).SetInt64(base) + return u +} + // Set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Int256) Set(value big.Int) (*Int256, error) { diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 3cf3dbae1e..743d9ab172 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -123,21 +123,28 @@ func TestInt256Set(t *testing.T) { // TestCopy tests the duplication of an existing Int256 variable func TestInt256Copy(t *testing.T) { - for _, tc := range int256TestCases { - t.Run(tc.name, func(t *testing.T) { - if !tc.expectsError { - r, err := NewInt256().Set(*tc.baseInteger) - if err != nil { - t.Fatalf("got unexpected error when creating new Int256: %v", err) - } + // pick test value + i := new(big.Int).Exp(big.NewInt(-2), big.NewInt(128), nil) // -2^128 + v, err := NewInt256().Set(*i) + if err != nil { + t.Fatalf("got unexpected error when creating new Int256: %v", err) + } - c := NewInt256().Copy(r) + // copy picked value + c := NewInt256().Copy(v) - if !c.Equals(r) { - t.Fatalf("copy of Int256 %v has an unequal value of %v", r, c) - } - } - }) + if !c.Equals(v) { + t.Fatalf("copy of Int256 %v has an unequal value of %v", v, c) + } + + _, err = v.Add(v, Int256From(1)) + if err != nil { + t.Fatalf("got unexpected error when increasing test case %v: %v", v, err) + } + + // value of copy should not have changed + if c.Equals(v) { + t.Fatalf("copy of Int256 %v had an unexpected change of value to %v", v, c) } } diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 7d02714a83..3cd1cc4693 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -39,9 +39,9 @@ func NewUint256() *Uint256 { return u } -// Uint64ToUint256 creates a Uint256 struct based on the given uint64 param +// Uint256From creates a Uint256 struct based on the given uint64 param // any uint64 is valid as a Uint256 -func Uint64ToUint256(base uint64) *Uint256 { +func Uint256From(base uint64) *Uint256 { u := NewUint256() u.value = *new(big.Int).SetUint64(base) return u diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 1aea0544ff..d426c5970f 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -102,21 +102,28 @@ func TestUint256Set(t *testing.T) { // TestCopy tests the duplication of an existing Uint256 variable func TestUint256Copy(t *testing.T) { - for _, tc := range uint256TestCases { - t.Run(tc.name, func(t *testing.T) { - if !tc.expectsError { - r, err := NewUint256().Set(*tc.baseInteger) - if err != nil { - t.Fatalf("got unexpected error when creating new Uint256: %v", err) - } + // pick test value + i := new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil) // 2^128 + v, err := NewUint256().Set(*i) + if err != nil { + t.Fatalf("got unexpected error when creating new Uint256: %v", err) + } - c := NewUint256().Copy(r) + // copy picked value + c := NewUint256().Copy(v) - if !c.Equals(r) { - t.Fatalf("copy of Uint256 %v has an unequal value of %v", r, c) - } - } - }) + if !c.Equals(v) { + t.Fatalf("copy of Uint256 %v has an unequal value of %v", v, c) + } + + _, err = v.Add(v, Uint256From(1)) + if err != nil { + t.Fatalf("got unexpected error when increasing test case %v: %v", v, err) + } + + // value of copy should not have changed + if c.Equals(v) { + t.Fatalf("copy of Uint256 %v had an unexpected change of value to %v", v, c) } } diff --git a/swap/peer.go b/swap/peer.go index 1cdd12537d..e8895f1cc0 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -167,7 +167,7 @@ func (p *Peer) createCheque() (*Cheque, error) { if err != nil { return nil, fmt.Errorf("error getting price from oracle: %v", err) } - price := int256.Uint64ToUint256(oraclePrice) + price := int256.Uint256From(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() newCumulativePayout, err := int256.NewUint256().Add(cumulativePayout, price) diff --git a/swap/protocol_test.go b/swap/protocol_test.go index 34af07b0a3..fa101d61ae 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -135,7 +135,7 @@ func correctSwapHandshakeMsg(swap *Swap) *HandshakeMsg { // TestHandshake tests the correct handshake scenario func TestHandshake(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint256From(0)) defer clean() if err != nil { t.Fatal(err) @@ -153,7 +153,7 @@ func TestHandshake(t *testing.T) { // TestHandshakeInvalidChainID tests that a handshake with the wrong chain id is rejected func TestHandshakeInvalidChainID(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint256From(0)) defer clean() if err != nil { t.Fatal(err) @@ -175,7 +175,7 @@ func TestHandshakeInvalidChainID(t *testing.T) { // TestHandshakeEmptyContract tests that a handshake with an empty contract address is rejected func TestHandshakeEmptyContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint256From(0)) defer clean() if err != nil { t.Fatal(err) @@ -197,7 +197,7 @@ func TestHandshakeEmptyContract(t *testing.T) { // TestHandshakeInvalidContract tests that a handshake with an address that's not a valid chequebook func TestHandshakeInvalidContract(t *testing.T) { // setup the protocolTester, which will allow protocol testing by sending messages - protocolTester, clean, err := newSwapTester(t, nil, int256.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, nil, int256.Uint256From(0)) defer clean() if err != nil { t.Fatal(err) @@ -223,7 +223,7 @@ func TestHandshakeInvalidContract(t *testing.T) { func TestEmitCheque(t *testing.T) { testBackend := newTestBackend(t) - protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint64ToUint256(0)) + protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint256From(0)) defer clean() if err != nil { t.Fatal(err) @@ -243,7 +243,7 @@ func TestEmitCheque(t *testing.T) { // gasPrice on testBackend == 1 // estimated gas costs == 50000 // cheque should be sent if the accumulated amount of uncashed cheques is worth more than 100000 - balance := int256.Uint64ToUint256(100001) + balance := int256.Uint256From(100001) balanceValue := balance.Value() if err := testDeploy(context.Background(), debitorSwap, balance); err != nil { @@ -331,7 +331,7 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint64ToUint256(DefaultPaymentThreshold*2)) + protocolTester, clean, err := newSwapTester(t, testBackend, int256.Uint256From(DefaultPaymentThreshold*2)) defer clean() if err != nil { t.Fatal(err) @@ -381,7 +381,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal("Expected pending cheque") } - if !pending.CumulativePayout.Equals(int256.Uint64ToUint256(expectedAmount)) { + if !pending.CumulativePayout.Equals(int256.Uint256From(expectedAmount)) { t.Fatalf("Expected cheque cumulative payout to be %d, but is %v", expectedAmount, pending.CumulativePayout) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index e3b8be9e70..9535c96256 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -161,7 +161,7 @@ func newSimServiceMap(params *swapSimulationParams) map[string]simulation.Servic ts.spec.Hook = protocols.NewAccounting(balance) ts.swap = balance // deploy the accounting to the `SimulatedBackend` - err = testDeploy(context.Background(), balance, int256.Uint64ToUint256(100000*RetrieveRequestPrice)) + err = testDeploy(context.Background(), balance, int256.Uint256From(100000*RetrieveRequestPrice)) if err != nil { return nil, nil, err } @@ -427,7 +427,7 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatalf("Expected symmetric cheques payout, but they are not: %v vs %v", cheque1.CumulativePayout, cheque2.CumulativePayout) } - if !cheque2.CumulativePayout.Equals(int256.Uint64ToUint256(expectedPayout)) { + if !cheque2.CumulativePayout.Equals(int256.Uint256From(expectedPayout)) { t.Fatalf("Expected %d in cumulative payout, got %v", expectedPayout, cheque1.CumulativePayout) } @@ -663,7 +663,7 @@ func waitForChequeProcessed(t *testing.T, backend *swapTestBackend, counter metr p.lock.Lock() lastPayout := p.getLastSentCumulativePayout() p.lock.Unlock() - if !lastPayout.Equals(int256.Uint64ToUint256(expectedLastPayout)) { + if !lastPayout.Equals(int256.Uint256From(expectedLastPayout)) { time.Sleep(5 * time.Millisecond) continue } else { diff --git a/swap/swap.go b/swap/swap.go index 3a3333738a..f34a096eb5 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -440,7 +440,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque return protocols.Break(err) } - costsMultiplier := int256.Uint64ToUint256(2) + costsMultiplier := int256.Uint256From(2) costThreshold, err := int256.NewUint256().Mul(transactionCosts, costsMultiplier) if err != nil { return err @@ -519,7 +519,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, return nil, err } - actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, int256.Uint64ToUint256(expectedAmount)) + actualAmount, err := cheque.verifyChequeAgainstLast(lastCheque, int256.Uint256From(expectedAmount)) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index 38d3f61453..394b545119 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -434,7 +434,7 @@ func TestStartChequebookFailure(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, config.testBackend) defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint256From(0)) if err != nil { t.Fatal(err) } @@ -493,7 +493,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint256From(0)) if err != nil { t.Fatal(err) } @@ -519,7 +519,7 @@ func TestStartChequebookSuccess(t *testing.T) { defer clean() // deploy a chequebook - err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint256From(0)) if err != nil { t.Fatal(err) } @@ -551,7 +551,7 @@ func TestStartChequebookSuccess(t *testing.T) { func TestDisconnectThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, int256.Uint64ToUint256(0)) + testDeploy(context.Background(), swap, int256.Uint256From(0)) testPeer := newDummyPeer() swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) @@ -577,7 +577,7 @@ func TestDisconnectThreshold(t *testing.T) { func TestPaymentThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, int256.Uint64ToUint256(DefaultPaymentThreshold)) + testDeploy(context.Background(), swap, int256.Uint256From(DefaultPaymentThreshold)) testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) if err := swap.Add(-int64(DefaultPaymentThreshold), testPeer.Peer); err != nil { @@ -586,7 +586,7 @@ func TestPaymentThreshold(t *testing.T) { var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(int256.Uint64ToUint256(DefaultPaymentThreshold)) { + if !cheque.CumulativePayout.Equals(int256.Uint256From(DefaultPaymentThreshold)) { t.Fatal() } } @@ -610,11 +610,11 @@ func TestResetBalance(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err := testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(0)) + err := testDeploy(ctx, creditorSwap, int256.Uint256From(0)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, int256.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, debitorSwap, int256.Uint256From(testAmount)) if err != nil { t.Fatal(err) } @@ -699,11 +699,11 @@ func TestDebtCheques(t *testing.T) { defer cleanup() ctx := context.Background() - if err := testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(0)); err != nil { + if err := testDeploy(ctx, creditorSwap, int256.Uint256From(0)); err != nil { t.Fatal(err) } - debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, int256.Uint64ToUint256((DefaultPaymentThreshold * 2))) + debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, int256.Uint256From((DefaultPaymentThreshold * 2))) if err != nil { t.Fatal(err) } @@ -715,7 +715,7 @@ func TestDebtCheques(t *testing.T) { } // create debt cheque - chequeAmount := int256.Uint64ToUint256(ChequeDebtTolerance * 2) + chequeAmount := int256.Uint256From(ChequeDebtTolerance * 2) cheque, err := newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) @@ -731,7 +731,7 @@ func TestDebtCheques(t *testing.T) { } // now create a (barely) admissible cheque - chequeAmount = int256.Uint64ToUint256(ChequeDebtTolerance) + chequeAmount = int256.Uint256From(ChequeDebtTolerance) cheque, err = newSignedTestCheque(debitorChequebook.ContractParams().ContractAddress, creditorSwap.owner.address, chequeAmount, ownerKey) if err != nil { t.Fatal(err) @@ -964,7 +964,7 @@ func TestVerifyContract(t *testing.T) { defer clean() // deploy a new swap contract - err := testDeploy(context.TODO(), swap, int256.Uint64ToUint256(0)) + err := testDeploy(context.TODO(), swap, int256.Uint256From(0)) if err != nil { t.Fatalf("Error in deploy: %v", err) } @@ -1102,7 +1102,7 @@ func TestPeerVerifyChequePropertiesInvalidCheque(t *testing.T) { // TestPeerVerifyChequeAgainstLast tests that verifyChequeAgainstLast accepts a cheque with higher amount func TestPeerVerifyChequeAgainstLast(t *testing.T) { - increase := int256.Uint64ToUint256(10) + increase := int256.Uint256From(10) oldCheque := newTestCheque() newCheque := newTestCheque() @@ -1123,7 +1123,7 @@ func TestPeerVerifyChequeAgainstLast(t *testing.T) { // TestPeerVerifyChequeAgainstLastInvalid tests that verifyChequeAgainstLast rejects cheques with lower amount or an unexpected value func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { - increase := int256.Uint64ToUint256(10) + increase := int256.Uint256From(10) // cheque with same or lower amount oldCheque := newTestCheque() @@ -1136,7 +1136,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := int256.NewUint256().Add(increase, int256.Uint64ToUint256(5)) + cumulativePayoutIncrease, err := int256.NewUint256().Add(increase, int256.Uint256From(5)) if err != nil { t.Fatal(err) } @@ -1176,7 +1176,7 @@ func TestPeerProcessAndVerifyCheque(t *testing.T) { // create another cheque with higher amount otherCheque := newTestCheque() - _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, int256.Uint64ToUint256(10)) + _, err = otherCheque.CumulativePayout.Add(cheque.CumulativePayout, int256.Uint256From(10)) if err != nil { t.Fatal(err) } @@ -1224,7 +1224,7 @@ func TestPeerProcessAndVerifyChequeInvalid(t *testing.T) { // invalid cheque because amount is lower otherCheque := newTestCheque() - _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, int256.Uint64ToUint256(10)) + _, err := otherCheque.CumulativePayout.Sub(cheque.CumulativePayout, int256.Uint256From(10)) if err != nil { t.Fatal(err) } @@ -1272,11 +1272,11 @@ func TestSwapLogToFile(t *testing.T) { testAmount := DefaultPaymentThreshold + 42 ctx := context.Background() - err = testDeploy(ctx, creditorSwap, int256.Uint64ToUint256(testAmount)) + err = testDeploy(ctx, creditorSwap, int256.Uint256From(testAmount)) if err != nil { t.Fatal(err) } - err = testDeploy(ctx, debitorSwap, int256.Uint64ToUint256(0)) + err = testDeploy(ctx, debitorSwap, int256.Uint256From(0)) if err != nil { t.Fatal(err) } @@ -1341,7 +1341,7 @@ func TestPeerGetLastSentCumulativePayout(t *testing.T) { _, peer, clean := newTestSwapAndPeer(t, ownerKey) defer clean() - if !peer.getLastSentCumulativePayout().Equals(int256.Uint64ToUint256(0)) { + if !peer.getLastSentCumulativePayout().Equals(int256.Uint256From(0)) { t.Fatalf("last cumulative payout should be 0 in the beginning, was %v", peer.getLastSentCumulativePayout()) } @@ -1363,7 +1363,7 @@ func TestAvailableBalance(t *testing.T) { cleanup := setupContractTest() defer cleanup() - depositAmount := int256.Uint64ToUint256(9000 * RetrieveRequestPrice) + depositAmount := int256.Uint256From(9000 * RetrieveRequestPrice) // deploy a chequebook err := testDeploy(context.TODO(), swap, depositAmount) @@ -1385,7 +1385,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatalf("available balance not equal to deposited amount. available balance: %v, deposit amount: %v", availableBalance, depositAmount) } // withdraw 50 - withdrawAmount := int256.Uint64ToUint256(50) + withdrawAmount := int256.Uint256From(50) netDeposit, err := int256.NewUint256().Sub(depositAmount, withdrawAmount) if err != nil { t.Fatal(err) @@ -1426,7 +1426,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatal(err) } // verify available balance - expectedBalance, err := int256.NewUint256().Sub(netDeposit, int256.Uint64ToUint256(chequeAmount)) + expectedBalance, err := int256.NewUint256().Sub(netDeposit, int256.Uint256From(chequeAmount)) if err != nil { t.Fatal(err) } From c0ddb1b59300d12dd6a7b562ef7c08f8d72cf613 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 15:48:50 -0300 Subject: [PATCH 32/70] int256: small change to test cases names --- swap/int256/int256_test.go | 26 +++++++++++++------------- swap/int256/uint256_test.go | 22 +++++++++++----------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 743d9ab172..ec09226946 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -32,69 +32,69 @@ type testCase struct { var int256TestCases = []testCase{ { - name: "base 0", + name: "case 0", baseInteger: big.NewInt(0), expectsError: false, }, // negative numbers { - name: "base -1", + name: "case -1", baseInteger: big.NewInt(-1), expectsError: false, }, { - name: "base -1 * 2^8", + name: "case -1 * 2^8", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: false, }, { - name: "base -1 * 2^64", + name: "case -1 * 2^64", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: false, }, { - name: "base -1 * 2^255", + name: "case -1 * 2^255", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), expectsError: false, }, { - name: "base -1 * 2^255 - 1", + name: "case -1 * 2^255 - 1", baseInteger: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), expectsError: true, }, { - name: "base -1 * 2^512", + name: "case -1 * 2^512", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), expectsError: true, }, // positive numbers { - name: "base 1", + name: "case 1", baseInteger: big.NewInt(1), expectsError: false, }, { - name: "base 2^8", + name: "case 2^8", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), expectsError: false, }, { - name: "base 2^128", + name: "case 2^128", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), expectsError: false, }, { - name: "base 2^255 - 1", + name: "case 2^255 - 1", baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), expectsError: false, }, { - name: "base 2^255", + name: "case 2^255", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), expectsError: true, }, { - name: "base 2^512", + name: "case 2^512", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index d426c5970f..0348a874d7 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -26,54 +26,54 @@ import ( var uint256TestCases = []testCase{ { - name: "base 0", + name: "case 0", baseInteger: big.NewInt(0), expectsError: false, }, // negative numbers { - name: "base -1", + name: "case -1", baseInteger: big.NewInt(-1), expectsError: true, }, { - name: "base -1 * 2^8", + name: "case -1 * 2^8", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: true, }, { - name: "base -1 * 2^64", + name: "case -1 * 2^64", baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: true, }, // positive numbers { - name: "base 1", + name: "case 1", baseInteger: big.NewInt(1), expectsError: false, }, { - name: "base 2^8", + name: "case 2^8", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), expectsError: false, }, { - name: "base 2^128", + name: "case 2^128", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), expectsError: false, }, { - name: "base 2^256 - 1", + name: "case 2^256 - 1", baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), expectsError: false, }, { - name: "base 2^256", + name: "case 2^256", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), expectsError: true, }, { - name: "base 2^512", + name: "case 2^512", baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, @@ -100,7 +100,7 @@ func TestUint256Set(t *testing.T) { } } -// TestCopy tests the duplication of an existing Uint256 variable +// TestCopy tests the du:heartplication of an existing Uint256 variable func TestUint256Copy(t *testing.T) { // pick test value i := new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil) // 2^128 From 2fe932732a21c4c2963aff58f013ccc072578f52 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 24 Feb 2020 17:02:22 -0300 Subject: [PATCH 33/70] int256: add comments to test cases array --- swap/int256/int256_test.go | 39 ++++++++++++++++++++----------------- swap/int256/uint256_test.go | 31 ++++++++++++++++------------- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index ec09226946..236f88b548 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -26,76 +26,79 @@ import ( type testCase struct { name string - baseInteger *big.Int + value *big.Int expectsError bool } +// the following test cases cover a range of values to be used to create int256 variables +// these variables are expected to be created successfully when using integer values +// contained in the closed interval between -2^255 and 2^255 - 1 var int256TestCases = []testCase{ { name: "case 0", - baseInteger: big.NewInt(0), + value: big.NewInt(0), expectsError: false, }, // negative numbers { name: "case -1", - baseInteger: big.NewInt(-1), + value: big.NewInt(-1), expectsError: false, }, { name: "case -1 * 2^8", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: false, }, { name: "case -1 * 2^64", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: false, }, { name: "case -1 * 2^255", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), expectsError: false, }, { name: "case -1 * 2^255 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), + value: new(big.Int).Sub(new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)), big.NewInt(1)), expectsError: true, }, { name: "case -1 * 2^512", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil)), expectsError: true, }, // positive numbers { name: "case 1", - baseInteger: big.NewInt(1), + value: big.NewInt(1), expectsError: false, }, { name: "case 2^8", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), expectsError: false, }, { name: "case 2^128", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), expectsError: false, }, { name: "case 2^255 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), + value: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)), expectsError: false, }, { name: "case 2^255", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), expectsError: true, }, { name: "case 2^512", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, } @@ -104,7 +107,7 @@ var int256TestCases = []testCase{ func TestInt256Set(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewInt256().Set(*tc.baseInteger) + result, err := NewInt256().Set(*tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Int256, but got none") } @@ -113,8 +116,8 @@ func TestInt256Set(t *testing.T) { t.Fatalf("got unexpected error when creating new Int256: %v", err) } resultValue := result.Value() - if (&resultValue).Cmp(tc.baseInteger) != 0 { - t.Fatalf("expected value of %v, got %v instead", tc.baseInteger, result.value) + if (&resultValue).Cmp(tc.value) != 0 { + t.Fatalf("expected value of %v, got %v instead", tc.value, result.value) } } }) @@ -164,7 +167,7 @@ func TestInt256Store(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewInt256().Set(*tc.baseInteger) + r, err := NewInt256().Set(*tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 0348a874d7..4b7ae837d5 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -24,57 +24,60 @@ import ( "github.com/ethersphere/swarm/state" ) +// the following test cases cover a range of values to be used to create uint256 variables +// these variables are expected to be created successfully when using integer values +// contained in the closed interval between 0 and 2^256 var uint256TestCases = []testCase{ { name: "case 0", - baseInteger: big.NewInt(0), + value: big.NewInt(0), expectsError: false, }, // negative numbers { name: "case -1", - baseInteger: big.NewInt(-1), + value: big.NewInt(-1), expectsError: true, }, { name: "case -1 * 2^8", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), expectsError: true, }, { name: "case -1 * 2^64", - baseInteger: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), + value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil)), expectsError: true, }, // positive numbers { name: "case 1", - baseInteger: big.NewInt(1), + value: big.NewInt(1), expectsError: false, }, { name: "case 2^8", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), expectsError: false, }, { name: "case 2^128", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil), expectsError: false, }, { name: "case 2^256 - 1", - baseInteger: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), + value: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)), expectsError: false, }, { name: "case 2^256", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), expectsError: true, }, { name: "case 2^512", - baseInteger: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), + value: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, } @@ -83,7 +86,7 @@ var uint256TestCases = []testCase{ func TestUint256Set(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewUint256().Set(*tc.baseInteger) + result, err := NewUint256().Set(*tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Uint256, but got none") } @@ -92,8 +95,8 @@ func TestUint256Set(t *testing.T) { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } resultValue := result.Value() - if (&resultValue).Cmp(tc.baseInteger) != 0 { - t.Fatalf("expected value of %v, got %v instead", tc.baseInteger, result.value) + if (&resultValue).Cmp(tc.value) != 0 { + t.Fatalf("expected value of %v, got %v instead", tc.value, result.value) } } }) @@ -143,7 +146,7 @@ func TestUint256Store(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewUint256().Set(*tc.baseInteger) + r, err := NewUint256().Set(*tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } From 51de0617f35c247fce65a07d9bfb42ee9d2c768e Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 26 Feb 2020 16:44:22 -0300 Subject: [PATCH 34/70] int256: rename Int64ToInt256 function to Int256From swap: refactor TestTriggerPaymentThreshold, TestMultiChequeSimulation & TestDebtCheques functions --- swap/int256/int256.go | 12 ++---------- swap/peer.go | 12 ++++++------ swap/protocol_test.go | 8 +++++--- swap/simulations_test.go | 26 ++++++++++++++++++++++---- swap/swap.go | 2 +- swap/swap_test.go | 6 +++++- 6 files changed, 41 insertions(+), 25 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 603d335669..e8019d2a11 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -44,9 +44,9 @@ func NewInt256() *Int256 { return u } -// Int64ToInt256 creates a Int256 struct based on the given int64 param +// Int256From creates a Int256 struct based on the given int64 param // any int64 is valid as a Int256 -func Int64ToInt256(base int64) *Int256 { +func Int256From(base int64) *Int256 { u := NewInt256() u.value = *new(big.Int).SetInt64(base) return u @@ -57,14 +57,6 @@ func (u *Int256) Value() big.Int { return u.value } -// Int256From creates a Int256 struct based on the given int64 param -// any int64 is valid as a Int256 -func Int256From(base int64) *Int256 { - u := NewInt256() - u.value = *new(big.Int).SetInt64(base) - return u -} - // Set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Int256) Set(value big.Int) (*Int256, error) { diff --git a/swap/peer.go b/swap/peer.go index 44d2810f33..2aa9ef3102 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -38,13 +38,13 @@ type Peer struct { *protocols.Peer lock sync.RWMutex swap *Swap - beneficiary common.Address // address of the peers chequebook owner - contractAddress common.Address // address of the peers chequebook - lastReceivedCheque *Cheque // last cheque we received from the peer - lastSentCheque *Cheque // last cheque that was sent to peer that was confirmed - pendingCheque *Cheque // last cheque that was sent to peer but is not yet confirmed + beneficiary common.Address // address of the peers chequebook owner + contractAddress common.Address // address of the peers chequebook + lastReceivedCheque *Cheque // last cheque we received from the peer + lastSentCheque *Cheque // last cheque that was sent to peer that was confirmed + pendingCheque *Cheque // last cheque that was sent to peer but is not yet confirmed balance *int256.Int256 // current balance of the peer - logger log.Logger // logger for swap related messages and audit trail with peer identifier + logger log.Logger // logger for swap related messages and audit trail with peer identifier } // NewPeer creates a new swap Peer instance diff --git a/swap/protocol_test.go b/swap/protocol_test.go index eabd3e8072..044296a357 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -365,15 +365,17 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal(err) } - pt, err := int256.NewInt256().Set(DefaultPaymentThreshold.Value()) + paymentThreshold := DefaultPaymentThreshold.Value() + newBalance, err := int256.NewInt256().Set(paymentThreshold) if err != nil { t.Fatal(err) } - b, err := int256.NewInt256().Mul(int256.Int256From(-1), pt) + _, err = newBalance.Mul(newBalance, int256.Int256From(-1)) if err != nil { t.Fatal(err) } - if err = creditor.setBalance(-int64(DefaultPaymentThreshold)); err != nil { + + if err = creditor.setBalance(newBalance); err != nil { t.Fatal(err) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index b2c2940e70..91827df159 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -341,9 +341,10 @@ func TestMultiChequeSimulation(t *testing.T) { } paymentThreshold := debitorSvc.swap.params.PaymentThreshold + pt := paymentThreshold.Value() chequesAmount := 4 - msgsPerCheque := (uint64(paymentThreshold) / msgPrice) + 1 // +1 to round up without casting to float + msgsPerCheque := (pt.Uint64() / msgPrice) + 1 // +1 to round up without casting to float msgAmount := int(msgsPerCheque) * chequesAmount log.Debug("sending %d messages", msgAmount) @@ -383,14 +384,31 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatal(err) } + mp := new(big.Int).SetUint64(msgPrice) + price, err := int256.NewInt256().Set(*mp) + if err != nil { + t.Fatal(err) + } + // check if cheque should have been sent - balanceAfterMessage := debitorBalance - int64(msgPrice) - if balanceAfterMessage <= -paymentThreshold { + balanceAfterMessage, err := int256.NewInt256().Sub(debitorBalance, price) + if err != nil { + t.Fatal(err) + } + + threshold, err := int256.NewInt256().Set(paymentThreshold.Value()) + if err != nil { + t.Fatal(err) + } + + pt, err := int256.NewInt256().Mul(threshold, int256.Int256From(-1)) + if balanceAfterMessage.Cmp(pt) <= 0 { // we need to wait a bit in order to give time for the cheque to be processed if err := waitForChequeProcessed(t, params.backend, counter, lastCount, debitorSvc.swap.peers[creditor], expectedPayout); err != nil { t.Fatal(err) } - expectedPayout += uint64(-balanceAfterMessage) + b := balanceAfterMessage.Value() + expectedPayout += (&b).Uint64() } lastCount++ diff --git a/swap/swap.go b/swap/swap.go index 6fe42c8181..6e9916f55d 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -561,7 +561,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, // check if this new balance would put creditor into debt if newBalance.Cmp(tolerance) == -1 { - return nil, fmt.Errorf("received cheque would result in balance %d which exceeds tolerance %d and would cause debt", newBalance, ChequeDebtTolerance) + return nil, fmt.Errorf("received cheque would result in balance %v which exceeds tolerance %d and would cause debt", newBalance, ChequeDebtTolerance) } if err := p.setLastReceivedCheque(cheque); err != nil { diff --git a/swap/swap_test.go b/swap/swap_test.go index eb923d46c0..06fbca57c9 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -721,7 +721,11 @@ func TestDebtCheques(t *testing.T) { t.Fatal(err) } - debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, int256.Uint256From((DefaultPaymentThreshold * 2))) + amount, err := int256.NewUint256().Mul(&DefaultPaymentThreshold, int256.Uint256From(2)) + if err != nil { + t.Fatal(err) + } + debitorChequebook, err := testDeployWithPrivateKey(ctx, testBackend, ownerKey, ownerAddress, amount) if err != nil { t.Fatal(err) } From cc0ed2a4132d9f78e30dd336fd12d7702b0e6dd4 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 27 Feb 2020 12:23:17 -0300 Subject: [PATCH 35/70] api, main, swap: remove de-reference for default swap thresholds --- api/config.go | 4 ++-- cmd/swarm/config_test.go | 4 ++-- swap/common_test.go | 4 ++-- swap/config.go | 4 ++-- swap/protocol_test.go | 6 +++--- swap/swap_test.go | 12 ++++++------ 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/api/config.go b/api/config.go index b11ad707f3..f2e8f71d98 100644 --- a/api/config.go +++ b/api/config.go @@ -96,8 +96,8 @@ func NewConfig() *Config { SwapEnabled: false, SwapSkipDeposit: false, SwapDepositAmount: swap.DefaultDepositAmount, - SwapPaymentThreshold: &swap.DefaultPaymentThreshold, - SwapDisconnectThreshold: &swap.DefaultDisconnectThreshold, + SwapPaymentThreshold: swap.DefaultPaymentThreshold, + SwapDisconnectThreshold: swap.DefaultDisconnectThreshold, SwapLogPath: "", HiveParams: network.NewHiveParams(), Pss: pss.NewParams(), diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index 69d69dd763..f8dbd7e9a9 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -228,13 +228,13 @@ func TestConfigCmdLineOverrides(t *testing.T) { t.Fatal(err) } - paymentThresholdOverride, err := int256.NewUint256().Add(&swap.DefaultPaymentThreshold, int256.Uint256From(1)) + paymentThresholdOverride, err := int256.NewUint256().Add(swap.DefaultPaymentThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } pt := paymentThresholdOverride.Value() - disconnectThresholdOverride, err := int256.NewUint256().Add(&swap.DefaultDisconnectThreshold, int256.Uint256From(1)) + disconnectThresholdOverride, err := int256.NewUint256().Add(swap.DefaultDisconnectThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } diff --git a/swap/common_test.go b/swap/common_test.go index 158f4bdd33..3a354ab995 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -82,8 +82,8 @@ func newDefaultParams(t *testing.T) *Params { return &Params{ BaseAddrs: network.NewBzzAddr(baseKey, nil), LogPath: "", - PaymentThreshold: &DefaultPaymentThreshold, - DisconnectThreshold: &DefaultDisconnectThreshold, + PaymentThreshold: DefaultPaymentThreshold, + DisconnectThreshold: DefaultDisconnectThreshold, } } diff --git a/swap/config.go b/swap/config.go index 58525bfc7c..a32b126f5e 100644 --- a/swap/config.go +++ b/swap/config.go @@ -43,5 +43,5 @@ const ( DefaultTransactionTimeout = 10 * time.Minute ) -var DefaultPaymentThreshold = *int256.Uint256From(defaultPaymentThreshold) -var DefaultDisconnectThreshold = *int256.Uint256From(defaultDisconnectThreshold) +var DefaultPaymentThreshold = int256.Uint256From(defaultPaymentThreshold) +var DefaultDisconnectThreshold = int256.Uint256From(defaultDisconnectThreshold) diff --git a/swap/protocol_test.go b/swap/protocol_test.go index 044296a357..d996085cd4 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -331,7 +331,7 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - depositAmount, err := int256.NewUint256().Mul(&DefaultPaymentThreshold, int256.Uint256From(2)) + depositAmount, err := int256.NewUint256().Mul(DefaultPaymentThreshold, int256.Uint256From(2)) if err != nil { t.Fatal(err) } @@ -360,7 +360,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { // set the balance to manually be at PaymentThreshold overDraft := int256.Uint256From(42) - expectedAmount, err := int256.NewUint256().Add(overDraft, &DefaultPaymentThreshold) + expectedAmount, err := int256.NewUint256().Add(overDraft, DefaultPaymentThreshold) if err != nil { t.Fatal(err) } @@ -515,7 +515,7 @@ func TestTriggerDisconnectThreshold(t *testing.T) { // set the balance to manually be at DisconnectThreshold overDraft := 42 - expectedBalance, err := int256.NewInt256().Set((&DefaultDisconnectThreshold).Value()) + expectedBalance, err := int256.NewInt256().Set((DefaultDisconnectThreshold).Value()) if err != nil { t.Fatal(err) } diff --git a/swap/swap_test.go b/swap/swap_test.go index 06fbca57c9..284f7675f1 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -367,7 +367,7 @@ func TestNewSwapFailure(t *testing.T) { configure: func(config *testSwapConfig) { config.prvkey = prvKey config.backendURL = "invalid backendURL" - params.PaymentThreshold = &DefaultPaymentThreshold + params.PaymentThreshold = DefaultPaymentThreshold config.skipDeposit = false config.factoryAddress = testBackend.factoryAddress }, @@ -581,7 +581,7 @@ func TestDisconnectThreshold(t *testing.T) { func TestPaymentThreshold(t *testing.T) { swap, clean := newTestSwap(t, ownerKey, nil) defer clean() - testDeploy(context.Background(), swap, &DefaultPaymentThreshold) + testDeploy(context.Background(), swap, DefaultPaymentThreshold) testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) amount := DefaultPaymentThreshold.Value() @@ -591,7 +591,7 @@ func TestPaymentThreshold(t *testing.T) { var cheque *Cheque _ = swap.store.Get(pendingChequeKey(testPeer.Peer.ID()), &cheque) - if !cheque.CumulativePayout.Equals(&DefaultPaymentThreshold) { + if !cheque.CumulativePayout.Equals(DefaultPaymentThreshold) { t.Fatal() } } @@ -612,7 +612,7 @@ func TestResetBalance(t *testing.T) { defer clean1() defer clean2() - testAmount, err := int256.NewUint256().Add(&DefaultPaymentThreshold, int256.Uint256From(42)) + testAmount, err := int256.NewUint256().Add(DefaultPaymentThreshold, int256.Uint256From(42)) if err != nil { t.Fatal(err) @@ -721,7 +721,7 @@ func TestDebtCheques(t *testing.T) { t.Fatal(err) } - amount, err := int256.NewUint256().Mul(&DefaultPaymentThreshold, int256.Uint256From(2)) + amount, err := int256.NewUint256().Mul(DefaultPaymentThreshold, int256.Uint256From(2)) if err != nil { t.Fatal(err) } @@ -1298,7 +1298,7 @@ func TestSwapLogToFile(t *testing.T) { } defer clean() - testAmount, err := int256.NewUint256().Add(&DefaultPaymentThreshold, int256.Uint256From(42)) + testAmount, err := int256.NewUint256().Add(DefaultPaymentThreshold, int256.Uint256From(42)) if err != nil { t.Fatal(err) } From 9254abec3e7e55f5e2bc749f09157071e5f93660 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 27 Feb 2020 15:51:17 -0300 Subject: [PATCH 36/70] main: small refactor to TestConfigCmdLineOverrides function --- cmd/swarm/config_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index f8dbd7e9a9..3d650a4b3d 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -228,17 +228,19 @@ func TestConfigCmdLineOverrides(t *testing.T) { t.Fatal(err) } + // add 1 to payment threshold paymentThresholdOverride, err := int256.NewUint256().Add(swap.DefaultPaymentThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } - pt := paymentThresholdOverride.Value() + paymentThreshold := paymentThresholdOverride.Value() + // add 1 to disconnect threshold disconnectThresholdOverride, err := int256.NewUint256().Add(swap.DefaultDisconnectThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } - dt := disconnectThresholdOverride.Value() + disconnectThreshold := disconnectThresholdOverride.Value() flags := []string{ fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "42", @@ -251,8 +253,8 @@ func TestConfigCmdLineOverrides(t *testing.T) { fmt.Sprintf("--%s", utils.DataDirFlag.Name), dir, fmt.Sprintf("--%s", utils.IPCPathFlag.Name), conf.IPCPath, "--verbosity", fmt.Sprintf("%d", *testutil.Loglevel), - fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), strconv.FormatUint(pt.Uint64(), 10), - fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), strconv.FormatUint(dt.Uint64(), 10), + fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), strconv.FormatUint(paymentThreshold.Uint64(), 10), + fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), strconv.FormatUint(disconnectThreshold.Uint64(), 10), fmt.Sprintf("--%s", SwarmEnablePinningFlag.Name), } From ce58332ef60bd1117dceac8723c21f9a591e286a Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 08:49:23 -0300 Subject: [PATCH 37/70] int256: rename Cmp to cmp to make it private since it was not used outside the package --- swap/int256/int256.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 39a861474f..162ad92208 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -72,13 +72,13 @@ func (u *Int256) Copy(v *Int256) *Int256 { } // Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field -func (u *Int256) Cmp(v *Int256) int { +func (u *Int256) cmp(v *Int256) int { return u.value.Cmp(&v.value) } // Equals returns true if the two Int256 structs have the same underlying values, false otherwise func (u *Int256) Equals(v *Int256) bool { - return u.Cmp(v) == 0 + return u.cmp(v) == 0 } // Add sets u to augend + addend and returns u as the sum From 308e98c4aaa4bc400449edcf165d661f0f9e9e46 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 09:06:47 -0300 Subject: [PATCH 38/70] int256: hard-code int256 and uint256 test cases value fields in which the literal number does not overflow --- swap/int256/int256_test.go | 2 +- swap/int256/uint256_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 236f88b548..2c5747420a 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -47,7 +47,7 @@ var int256TestCases = []testCase{ }, { name: "case -1 * 2^8", - value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + value: big.NewInt(-256), expectsError: false, }, { diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 4b7ae837d5..b96a27c529 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -41,7 +41,7 @@ var uint256TestCases = []testCase{ }, { name: "case -1 * 2^8", - value: new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil)), + value: big.NewInt(-256), expectsError: true, }, { @@ -57,7 +57,7 @@ var uint256TestCases = []testCase{ }, { name: "case 2^8", - value: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + value: big.NewInt(256), expectsError: false, }, { From 05ecc7cfad309ef325b6025fb8256c9acf881a95 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 10:17:10 -0300 Subject: [PATCH 39/70] int256: change signature of Int256 and Uint256 Copy methods to receive no parameters and instead copy the receiver struct and return it --- swap/cheque.go | 2 +- swap/int256/int256.go | 9 +++++---- swap/int256/int256_test.go | 2 +- swap/int256/uint256.go | 9 +++++---- swap/int256/uint256_test.go | 2 +- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/swap/cheque.go b/swap/cheque.go index 9d7ccfc4e8..eb0737cfa9 100644 --- a/swap/cheque.go +++ b/swap/cheque.go @@ -134,7 +134,7 @@ func (cheque *Cheque) verifyChequeProperties(p *Peer, expectedBeneficiary common // verifyChequeAgainstLast verifies that the amount is higher than in the previous cheque and the increase is as expected // returns the actual amount received in this cheque func (cheque *Cheque) verifyChequeAgainstLast(lastCheque *Cheque, expectedAmount *int256.Uint256) (*int256.Uint256, error) { - actualAmount := int256.NewUint256().Copy(cheque.CumulativePayout) + actualAmount := cheque.CumulativePayout.Copy() if lastCheque != nil { if cheque.CumulativePayout.Cmp(lastCheque.CumulativePayout) < 1 { diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 162ad92208..8cbac6a0f2 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -65,10 +65,11 @@ func (u *Int256) Set(value big.Int) (*Int256, error) { return u, nil } -// Copy sets the underlying value of u to a copy of the given Int256 param, and returns the modified receiver struct -func (u *Int256) Copy(v *Int256) *Int256 { - u.value = *new(big.Int).Set(&v.value) - return u +// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver +func (u *Int256) Copy() *Int256 { + v := NewInt256() + v.value = *new(big.Int).Set(&u.value) + return v } // Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 2c5747420a..cda47f0ba2 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -134,7 +134,7 @@ func TestInt256Copy(t *testing.T) { } // copy picked value - c := NewInt256().Copy(v) + c := v.Copy() if !c.Equals(v) { t.Fatalf("copy of Int256 %v has an unequal value of %v", v, c) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 3cd1cc4693..5dd2499386 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -65,10 +65,11 @@ func (u *Uint256) Set(value big.Int) (*Uint256, error) { return u, nil } -// Copy sets the underlying value of u to a copy of the given Uint256 param, and returns the modified receiver struct -func (u *Uint256) Copy(v *Uint256) *Uint256 { - u.value = *new(big.Int).Set(&v.value) - return u +// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver +func (u *Uint256) Copy() *Uint256 { + v := NewUint256() + v.value = *new(big.Int).Set(&u.value) + return v } // Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index b96a27c529..1aa6f13b46 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -113,7 +113,7 @@ func TestUint256Copy(t *testing.T) { } // copy picked value - c := NewUint256().Copy(v) + c := v.Copy() if !c.Equals(v) { t.Fatalf("copy of Uint256 %v has an unequal value of %v", v, c) From 25704d331f878612ef2ba50c6e9bd7de97abae65 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 17:27:59 -0300 Subject: [PATCH 40/70] int256: make Int256 Set function private, instead allow the constructor to receive a parameter to set the struct value to --- swap/int256/int256.go | 28 ++++++++++++++-------------- swap/int256/int256_test.go | 6 +++--- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 8cbac6a0f2..d0b7ea9426 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -32,11 +32,11 @@ type Int256 struct { var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)) // 2^255 - 1 -// NewInt256 creates a Int256 struct with an initial underlying value of zero -func NewInt256() *Int256 { +// NewInt256 creates a Int256 struct with an initial underlying value of the given param +// returns an error when the result falls outside of the signed 256-bit integer range +func NewInt256(value big.Int) (*Int256, error) { u := new(Int256) - u.value = *new(big.Int).Set(big.NewInt(0)) - return u + return u.set(value) } // Value returns the underlying private value for a Int256 struct @@ -47,14 +47,14 @@ func (u *Int256) Value() big.Int { // Int256From creates a Int256 struct based on the given int64 param // any int64 is valid as a Int256 func Int256From(base int64) *Int256 { - u := NewInt256() + u := new(Int256) u.value = *new(big.Int).SetInt64(base) return u } -// Set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct -// returns an error when the result falls outside of the unsigned 256-bit integer range -func (u *Int256) Set(value big.Int) (*Int256, error) { +// set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct +// returns an error when the result falls outside of the signed 256-bit integer range +func (u *Int256) set(value big.Int) (*Int256, error) { if value.Cmp(maxInt256) == 1 { return nil, fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) } @@ -67,7 +67,7 @@ func (u *Int256) Set(value big.Int) (*Int256, error) { // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Int256) Copy() *Int256 { - v := NewInt256() + v := new(Int256) v.value = *new(big.Int).Set(&u.value) return v } @@ -86,21 +86,21 @@ func (u *Int256) Equals(v *Int256) bool { // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Add(augend, addend *Int256) (*Int256, error) { sum := new(big.Int).Add(&augend.value, &addend.value) - return u.Set(*sum) + return u.set(*sum) } // Sub sets u to minuend - subtrahend and returns u as the difference // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Sub(minuend, subtrahend *Int256) (*Int256, error) { difference := new(big.Int).Sub(&minuend.value, &subtrahend.value) - return u.Set(*difference) + return u.set(*difference) } // Mul sets u to multiplicand * multiplier and returns u as the product // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { product := new(big.Int).Mul(&multiplicand.value, &multiplier.value) - return u.Set(*product) + return u.set(*product) } // String returns the string representation for Int256 structs @@ -126,7 +126,7 @@ func (u *Int256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - _, err := u.Set(value) + _, err := u.set(value) return err } @@ -142,6 +142,6 @@ func (u *Int256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { return nil } - _, err := u.Set(u.value) + _, err := u.set(u.value) return err } diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index cda47f0ba2..c28f2f248f 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -107,7 +107,7 @@ var int256TestCases = []testCase{ func TestInt256Set(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewInt256().Set(*tc.value) + result, err := NewInt256(*tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Int256, but got none") } @@ -128,7 +128,7 @@ func TestInt256Set(t *testing.T) { func TestInt256Copy(t *testing.T) { // pick test value i := new(big.Int).Exp(big.NewInt(-2), big.NewInt(128), nil) // -2^128 - v, err := NewInt256().Set(*i) + v, err := NewInt256(*i) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } @@ -167,7 +167,7 @@ func TestInt256Store(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewInt256().Set(*tc.value) + r, err := NewInt256(*tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } From 0dc050a408d5aa1cb4c74fb50d482d75746075b8 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 17:31:36 -0300 Subject: [PATCH 41/70] int256: make Uint256 Set function private, instead allow the constructor to receive a parameter to set the struct value to --- swap/int256/uint256.go | 21 ++++++++++----------- swap/int256/uint256_test.go | 6 +++--- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 5dd2499386..de8f19b9d6 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -33,16 +33,15 @@ var minUint256 = big.NewInt(0) var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)) // 2^256 - 1 // NewUint256 creates a Uint256 struct with an initial underlying value of zero -func NewUint256() *Uint256 { +func NewUint256(value big.Int) (*Uint256, error) { u := new(Uint256) - u.value = *new(big.Int).Set(big.NewInt(0)) - return u + return u.set(value) } // Uint256From creates a Uint256 struct based on the given uint64 param // any uint64 is valid as a Uint256 func Uint256From(base uint64) *Uint256 { - u := NewUint256() + u := new(Uint256) u.value = *new(big.Int).SetUint64(base) return u } @@ -54,7 +53,7 @@ func (u *Uint256) Value() big.Int { // Set assigns the underlying value of the given Uint256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the unsigned 256-bit integer range -func (u *Uint256) Set(value big.Int) (*Uint256, error) { +func (u *Uint256) set(value big.Int) (*Uint256, error) { if value.Cmp(maxUint256) == 1 { return nil, fmt.Errorf("cannot set Uint256 to %v as it overflows max value of %v", value, maxUint256) } @@ -67,7 +66,7 @@ func (u *Uint256) Set(value big.Int) (*Uint256, error) { // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Uint256) Copy() *Uint256 { - v := NewUint256() + v := new(Uint256) v.value = *new(big.Int).Set(&u.value) return v } @@ -86,21 +85,21 @@ func (u *Uint256) Equals(v *Uint256) bool { // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Add(augend, addend *Uint256) (*Uint256, error) { sum := new(big.Int).Add(&augend.value, &addend.value) - return u.Set(*sum) + return u.set(*sum) } // Sub sets u to minuend - subtrahend and returns u as the difference // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Sub(minuend, subtrahend *Uint256) (*Uint256, error) { difference := new(big.Int).Sub(&minuend.value, &subtrahend.value) - return u.Set(*difference) + return u.set(*difference) } // Mul sets u to multiplicand * multiplier and returns u as the product // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Mul(multiplicand, multiplier *Uint256) (*Uint256, error) { product := new(big.Int).Mul(&multiplicand.value, &multiplier.value) - return u.Set(*product) + return u.set(*product) } // String returns the string representation for Uint256 structs @@ -126,7 +125,7 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - _, err := u.Set(value) + _, err := u.set(value) return err } @@ -142,6 +141,6 @@ func (u *Uint256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { return nil } - _, err := u.Set(u.value) + _, err := u.set(u.value) return err } diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 1aa6f13b46..be1201ec72 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -86,7 +86,7 @@ var uint256TestCases = []testCase{ func TestUint256Set(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewUint256().Set(*tc.value) + result, err := NewUint256(*tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Uint256, but got none") } @@ -107,7 +107,7 @@ func TestUint256Set(t *testing.T) { func TestUint256Copy(t *testing.T) { // pick test value i := new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil) // 2^128 - v, err := NewUint256().Set(*i) + v, err := NewUint256(*i) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } @@ -146,7 +146,7 @@ func TestUint256Store(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewUint256().Set(*tc.value) + r, err := NewUint256(*tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } From f401aa503b367dcf6b3ca5e7422c52eb6d767516 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 11 Mar 2020 17:41:01 -0300 Subject: [PATCH 42/70] swap: replace constructor calls for Uint256 struct with the new signature, remove Set calls which are no longer allowed --- swap/api.go | 2 +- swap/cashout.go | 10 +++++----- swap/cashout_test.go | 2 +- swap/peer.go | 4 ++-- swap/swap.go | 2 +- swap/swap_test.go | 6 +++--- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/swap/api.go b/swap/api.go index b1cfc8ae4a..c016e8f285 100644 --- a/swap/api.go +++ b/swap/api.go @@ -91,7 +91,7 @@ func (s *Swap) AvailableBalance() (*int256.Uint256, error) { totalChequesWorth := new(big.Int).Sub(cashedChequesWorth, sentChequesWorth) tentativeLiquidBalance := new(big.Int).Add(contractLiquidBalance, totalChequesWorth) - return int256.NewUint256().Set(*tentativeLiquidBalance) + return int256.NewUint256(*tentativeLiquidBalance) } // PeerBalance returns the balance for a given peer diff --git a/swap/cashout.go b/swap/cashout.go index 9867d7642a..c860022176 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -97,7 +97,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - paidOut, err := int256.NewUint256().Set(*po) + paidOut, err := int256.NewUint256(*po) if err != nil { return nil, nil, err } @@ -107,21 +107,21 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - gasPrice, err := int256.NewUint256().Set(*gp) + gasPrice, err := int256.NewUint256(*gp) if err != nil { return nil, nil, err } - transactionCosts, err = int256.NewUint256().Mul(gasPrice, int256.Uint256From(CashChequeBeneficiaryTransactionCost)) + transactionCosts, err = new(int256.Uint256).Mul(gasPrice, int256.Uint256From(CashChequeBeneficiaryTransactionCost)) if err != nil { return nil, nil, err } if paidOut.Cmp(cheque.CumulativePayout) > 0 { - return int256.NewUint256(), transactionCosts, nil + return new(int256.Uint256), transactionCosts, nil } - expectedPayout, err = int256.NewUint256().Sub(cheque.CumulativePayout, paidOut) + expectedPayout, err = new(int256.Uint256).Sub(cheque.CumulativePayout, paidOut) if err != nil { return nil, nil, err } diff --git a/swap/cashout_test.go b/swap/cashout_test.go index a00d603fc9..d00cf5c907 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -74,7 +74,7 @@ func TestContractIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - paidOut, err := int256.NewUint256().Set(*result) + paidOut, err := int256.NewUint256(*result) if err != nil { t.Fatal(err) } diff --git a/swap/peer.go b/swap/peer.go index 3429684305..d0a1461534 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -121,7 +121,7 @@ func (p *Peer) getLastSentCumulativePayout() *int256.Uint256 { if lastCheque != nil { return lastCheque.CumulativePayout } - return int256.NewUint256() + return int256.Uint256From(0) } // the caller is expected to hold p.lock @@ -169,7 +169,7 @@ func (p *Peer) createCheque() (*Cheque, error) { price := int256.Uint256From(oraclePrice) cumulativePayout := p.getLastSentCumulativePayout() - newCumulativePayout, err := int256.NewUint256().Add(cumulativePayout, price) + newCumulativePayout, err := new(int256.Uint256).Add(cumulativePayout, price) if err != nil { return nil, err } diff --git a/swap/swap.go b/swap/swap.go index e50dc330c5..2001ab8333 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -392,7 +392,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque } costsMultiplier := int256.Uint256From(2) - costThreshold, err := int256.NewUint256().Mul(transactionCosts, costsMultiplier) + costThreshold, err := new(int256.Uint256).Mul(transactionCosts, costsMultiplier) if err != nil { return err } diff --git a/swap/swap_test.go b/swap/swap_test.go index 3d2bfa6465..a3b94f985c 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -1135,7 +1135,7 @@ func TestPeerVerifyChequeAgainstLastInvalid(t *testing.T) { // cheque with amount != increase oldCheque = newTestCheque() newCheque = newTestCheque() - cumulativePayoutIncrease, err := int256.NewUint256().Add(increase, int256.Uint256From(5)) + cumulativePayoutIncrease, err := new(int256.Uint256).Add(increase, int256.Uint256From(5)) if err != nil { t.Fatal(err) } @@ -1459,7 +1459,7 @@ func TestAvailableBalance(t *testing.T) { } // withdraw 50 withdrawAmount := int256.Uint256From(50) - netDeposit, err := int256.NewUint256().Sub(depositAmount, withdrawAmount) + netDeposit, err := new(int256.Uint256).Sub(depositAmount, withdrawAmount) if err != nil { t.Fatal(err) } @@ -1499,7 +1499,7 @@ func TestAvailableBalance(t *testing.T) { t.Fatal(err) } // verify available balance - expectedBalance, err := int256.NewUint256().Sub(netDeposit, int256.Uint256From(chequeAmount)) + expectedBalance, err := new(int256.Uint256).Sub(netDeposit, int256.Uint256From(chequeAmount)) if err != nil { t.Fatal(err) } From 7084544c3795dad813dc93ded66e8117825ed37e Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 12:12:32 -0300 Subject: [PATCH 43/70] int256: fix docstring for NewUint256 func --- swap/int256/uint256.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index de8f19b9d6..758a4337fe 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -32,7 +32,8 @@ type Uint256 struct { var minUint256 = big.NewInt(0) var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)) // 2^256 - 1 -// NewUint256 creates a Uint256 struct with an initial underlying value of zero +// NewUint256 creates a Uint256 struct with an initial underlying value of the given param +// returns an error when the result falls outside of the unsigned 256-bit integer range func NewUint256(value big.Int) (*Uint256, error) { u := new(Uint256) return u.set(value) From 68d0679114c9d58f4a91ecd30566bc48f3680afe Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 12:15:01 -0300 Subject: [PATCH 44/70] int256: reorder Int256 and Uint256 funcs for more clarity and consistency --- swap/int256/int256.go | 44 +++++++++++++++++++++--------------------- swap/int256/uint256.go | 34 ++++++++++++++++---------------- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index d0b7ea9426..aa622b301d 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -39,11 +39,6 @@ func NewInt256(value big.Int) (*Int256, error) { return u.set(value) } -// Value returns the underlying private value for a Int256 struct -func (u *Int256) Value() big.Int { - return u.value -} - // Int256From creates a Int256 struct based on the given int64 param // any int64 is valid as a Int256 func Int256From(base int64) *Int256 { @@ -52,6 +47,18 @@ func Int256From(base int64) *Int256 { return u } +// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver +func (u *Int256) Copy() *Int256 { + v := new(Int256) + v.value = *new(big.Int).Set(&u.value) + return v +} + +// Value returns the underlying private value for a Int256 struct +func (u *Int256) Value() big.Int { + return u.value +} + // set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) set(value big.Int) (*Int256, error) { @@ -65,23 +72,6 @@ func (u *Int256) set(value big.Int) (*Int256, error) { return u, nil } -// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver -func (u *Int256) Copy() *Int256 { - v := new(Int256) - v.value = *new(big.Int).Set(&u.value) - return v -} - -// Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field -func (u *Int256) cmp(v *Int256) int { - return u.value.Cmp(&v.value) -} - -// Equals returns true if the two Int256 structs have the same underlying values, false otherwise -func (u *Int256) Equals(v *Int256) bool { - return u.cmp(v) == 0 -} - // Add sets u to augend + addend and returns u as the sum // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Add(augend, addend *Int256) (*Int256, error) { @@ -103,6 +93,16 @@ func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { return u.set(*product) } +// cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field +func (u *Int256) cmp(v *Int256) int { + return u.value.Cmp(&v.value) +} + +// Equals returns true if the two Int256 structs have the same underlying values, false otherwise +func (u *Int256) Equals(v *Int256) bool { + return u.cmp(v) == 0 +} + // String returns the string representation for Int256 structs func (u *Int256) String() string { return u.value.String() diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 758a4337fe..0b18b5661f 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -47,6 +47,13 @@ func Uint256From(base uint64) *Uint256 { return u } +// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver +func (u *Uint256) Copy() *Uint256 { + v := new(Uint256) + v.value = *new(big.Int).Set(&u.value) + return v +} + // Value returns the underlying private value for a Uint256 struct func (u *Uint256) Value() big.Int { return u.value @@ -65,23 +72,6 @@ func (u *Uint256) set(value big.Int) (*Uint256, error) { return u, nil } -// Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver -func (u *Uint256) Copy() *Uint256 { - v := new(Uint256) - v.value = *new(big.Int).Set(&u.value) - return v -} - -// Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field -func (u *Uint256) Cmp(v *Uint256) int { - return u.value.Cmp(&v.value) -} - -// Equals returns true if the two Uint256 structs have the same underlying values, false otherwise -func (u *Uint256) Equals(v *Uint256) bool { - return u.Cmp(v) == 0 -} - // Add sets u to augend + addend and returns u as the sum // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Add(augend, addend *Uint256) (*Uint256, error) { @@ -103,6 +93,16 @@ func (u *Uint256) Mul(multiplicand, multiplier *Uint256) (*Uint256, error) { return u.set(*product) } +// Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field +func (u *Uint256) Cmp(v *Uint256) int { + return u.value.Cmp(&v.value) +} + +// Equals returns true if the two Uint256 structs have the same underlying values, false otherwise +func (u *Uint256) Equals(v *Uint256) bool { + return u.Cmp(v) == 0 +} + // String returns the string representation for Uint256 structs func (u *Uint256) String() string { return u.value.String() From 142a6b5908853ade69ae30cca6748e1a6bc4921b Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 12:25:09 -0300 Subject: [PATCH 45/70] int256: fix casing in Uint256 set docstring --- swap/int256/uint256.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 0b18b5661f..e4d84c972b 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -59,7 +59,7 @@ func (u *Uint256) Value() big.Int { return u.value } -// Set assigns the underlying value of the given Uint256 param to u, and returns the modified receiver struct +// set assigns the underlying value of the given Uint256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) set(value big.Int) (*Uint256, error) { if value.Cmp(maxUint256) == 1 { From 04bb9a55edea3fa8e0fc213877920764e3fb8be9 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 15:12:46 -0300 Subject: [PATCH 46/70] swap: replace constructor calls for Uint256 struct with the new signature, remove Set calls which are no longer allowed int256: make Int256 Cmp func public since it is used outside the package --- api/config.go | 2 +- swap/int256/int256.go | 8 ++++---- swap/peer.go | 2 +- swap/swap.go | 12 ++++++------ 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/api/config.go b/api/config.go index 28c22effad..8c1c31fe1d 100644 --- a/api/config.go +++ b/api/config.go @@ -60,7 +60,7 @@ type Config struct { SwapSkipDeposit bool // do not ask the user to deposit during boot sequence SwapDepositAmount uint64 // deposit amount to the chequebook SwapLogPath string // dir to swap related audit logs - SwapLogLevel int // log level of swap related audit logs + SwapLogLevel int // log level of swap related audit logs Contract common.Address // address of the chequebook contract SwapChequebookFactory common.Address // address of the chequebook factory contract // end of Swap configs diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 3f50b2df8d..3bc5ecefea 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -98,15 +98,15 @@ func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { return u.set(*product) } -// cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field -func (u *Int256) cmp(v *BigIntWrapper) int { +// Cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field +func (u *Int256) Cmp(v BigIntWrapper) int { value := v.Value() return u.value.Cmp(&value) } // Equals returns true if the two Int256 structs have the same underlying values, false otherwise -func (u *Int256) Equals(v *BigIntWrapper) bool { - return u.cmp(v) == 0 +func (u *Int256) Equals(v BigIntWrapper) bool { + return u.Cmp(v) == 0 } // String returns the string representation for Int256 structs diff --git a/swap/peer.go b/swap/peer.go index 2f4ad6e0c8..9b6eff63cb 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -140,7 +140,7 @@ func (p *Peer) getBalance() *int256.Int256 { func (p *Peer) updateBalance(amount *int256.Int256) error { //adjust the balance //if amount is negative, it will decrease, otherwise increase - newBalance, err := int256.NewInt256().Add(p.getBalance(), amount) + newBalance, err := new(int256.Int256).Add(p.getBalance(), amount) if err != nil { return err } diff --git a/swap/swap.go b/swap/swap.go index 46b37a9989..7da5878556 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -324,12 +324,12 @@ func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error) { func (s *Swap) checkPaymentThresholdAndSendCheque(swapPeer *Peer) error { balance := swapPeer.getBalance() thresholdValue := s.params.PaymentThreshold.Value() - threshold, err := int256.NewInt256().Set(thresholdValue) + threshold, err := int256.NewInt256(thresholdValue) if err != nil { return err } - negativeThreshold, err := int256.NewInt256().Mul(int256.Int256From(-1), threshold) + negativeThreshold, err := new(int256.Int256).Mul(int256.Int256From(-1), threshold) if err != nil { return err } @@ -383,7 +383,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque // as this is done by the creditor, receiving the cheque, the amount should be negative, // so that updateBalance will calculate balance + amount which result in reducing the peer's balance honeyAmount := int256.Int256From(int64(cheque.Honey)) - honey, err := int256.NewInt256().Mul(int256.Int256From(-1), honeyAmount) + honey, err := new(int256.Int256).Mul(int256.Int256From(-1), honeyAmount) if err != nil { return protocols.Break(err) } @@ -494,19 +494,19 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, } chequeHoney := new(big.Int).SetUint64(cheque.Honey) - honey, err := int256.NewInt256().Set(*chequeHoney) + honey, err := int256.NewInt256(*chequeHoney) if err != nil { return nil, err } // calculate tentative new balance after cheque is processed - newBalance, err := int256.NewInt256().Sub(p.getBalance(), honey) + newBalance, err := new(int256.Int256).Sub(p.getBalance(), honey) if err != nil { return nil, err } debtTolerance := big.NewInt(-int64(ChequeDebtTolerance)) - tolerance, err := int256.NewInt256().Set(*debtTolerance) + tolerance, err := int256.NewInt256(*debtTolerance) if err != nil { return nil, err } From 95f0d54e0457b570efba3c2ad6f4cb7ad126f975 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 16:09:36 -0300 Subject: [PATCH 47/70] cmd/swarm, swap: swap replace constructor calls in tests for Uint256 & Int256 structs with new signatures, remove Set calls which are no longer allowed --- cmd/swarm/config_test.go | 4 ++-- swap/protocol_test.go | 16 ++++++++-------- swap/simulations_test.go | 12 ++++++------ swap/swap_test.go | 18 +++++++++--------- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index 3d650a4b3d..1f25504ff7 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -229,14 +229,14 @@ func TestConfigCmdLineOverrides(t *testing.T) { } // add 1 to payment threshold - paymentThresholdOverride, err := int256.NewUint256().Add(swap.DefaultPaymentThreshold, int256.Uint256From(1)) + paymentThresholdOverride, err := new(int256.Uint256).Add(swap.DefaultPaymentThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } paymentThreshold := paymentThresholdOverride.Value() // add 1 to disconnect threshold - disconnectThresholdOverride, err := int256.NewUint256().Add(swap.DefaultDisconnectThreshold, int256.Uint256From(1)) + disconnectThresholdOverride, err := new(int256.Uint256).Add(swap.DefaultDisconnectThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } diff --git a/swap/protocol_test.go b/swap/protocol_test.go index d996085cd4..39dc85a11c 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -331,7 +331,7 @@ func TestEmitCheque(t *testing.T) { func TestTriggerPaymentThreshold(t *testing.T) { testBackend := newTestBackend(t) log.Debug("create test swap") - depositAmount, err := int256.NewUint256().Mul(DefaultPaymentThreshold, int256.Uint256From(2)) + depositAmount, err := new(int256.Uint256).Mul(DefaultPaymentThreshold, int256.Uint256From(2)) if err != nil { t.Fatal(err) } @@ -360,13 +360,13 @@ func TestTriggerPaymentThreshold(t *testing.T) { // set the balance to manually be at PaymentThreshold overDraft := int256.Uint256From(42) - expectedAmount, err := int256.NewUint256().Add(overDraft, DefaultPaymentThreshold) + expectedAmount, err := new(int256.Uint256).Add(overDraft, DefaultPaymentThreshold) if err != nil { t.Fatal(err) } paymentThreshold := DefaultPaymentThreshold.Value() - newBalance, err := int256.NewInt256().Set(paymentThreshold) + newBalance, err := int256.NewInt256(paymentThreshold) if err != nil { t.Fatal(err) } @@ -515,7 +515,7 @@ func TestTriggerDisconnectThreshold(t *testing.T) { // set the balance to manually be at DisconnectThreshold overDraft := 42 - expectedBalance, err := int256.NewInt256().Set((DefaultDisconnectThreshold).Value()) + expectedBalance, err := int256.NewInt256((DefaultDisconnectThreshold).Value()) if err != nil { t.Fatal(err) } @@ -605,7 +605,7 @@ func TestSwapRPC(t *testing.T) { fakeBalance2 := int256.Int256From(-100) // query a first time, should give error - balance := int256.NewInt256() + balance := new(int256.Int256) err = rpcclient.Call(balance, "swap_peerBalance", id1) // at this point no balance should be there: no peer registered with Swap if err == nil { @@ -614,7 +614,7 @@ func TestSwapRPC(t *testing.T) { log.Debug("servicenode balance", "balance", balance) // ...thus balance should be empty - if !balance.Equals(int256.NewInt256()) { + if !balance.Equals(new(int256.Int256)) { t.Fatalf("Expected balance to be empty but it is %v", balance) } @@ -663,12 +663,12 @@ func TestSwapRPC(t *testing.T) { } log.Debug("received balances", "allBalances", allBalances) - sum := int256.NewInt256() + sum := new(int256.Int256) for _, v := range allBalances { sum.Add(sum, v) } - fakeSum, err := int256.NewInt256().Add(fakeBalance1, fakeBalance2) + fakeSum, err := new(int256.Int256).Add(fakeBalance1, fakeBalance2) if err != nil { t.Fatal(err) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index f010b8aee7..591942ad09 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -386,23 +386,23 @@ func TestMultiChequeSimulation(t *testing.T) { } mp := new(big.Int).SetUint64(msgPrice) - price, err := int256.NewInt256().Set(*mp) + price, err := int256.NewInt256(*mp) if err != nil { t.Fatal(err) } // check if cheque should have been sent - balanceAfterMessage, err := int256.NewInt256().Sub(debitorBalance, price) + balanceAfterMessage, err := new(int256.Int256).Sub(debitorBalance, price) if err != nil { t.Fatal(err) } - threshold, err := int256.NewInt256().Set(paymentThreshold.Value()) + threshold, err := int256.NewInt256(paymentThreshold.Value()) if err != nil { t.Fatal(err) } - pt, err := int256.NewInt256().Mul(threshold, int256.Int256From(-1)) + pt, err := new(int256.Int256).Mul(threshold, int256.Int256From(-1)) if balanceAfterMessage.Cmp(pt) <= 0 { // we need to wait a bit in order to give time for the cheque to be processed if err := waitForChequeProcessed(t, params.backend, counter, lastCount, debitorSvc.swap.peers[creditor], expectedPayout); err != nil { @@ -432,7 +432,7 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatal(err) } - b2, err = int256.NewInt256().Mul(b2, int256.Int256From(-1)) + b2, err = new(int256.Int256).Mul(b2, int256.Int256From(-1)) if err != nil { t.Fatal(err) } @@ -629,7 +629,7 @@ func TestBasicSwapSimulation(t *testing.T) { if err != nil { return fmt.Errorf("expected counter balance for node %v to be found, but not found", node) } - pBalanceWithNode, err = int256.NewInt256().Mul(pBalanceWithNode, int256.Int256From(-1)) + pBalanceWithNode, err = new(int256.Int256).Mul(pBalanceWithNode, int256.Int256From(-1)) if err != nil { return err } diff --git a/swap/swap_test.go b/swap/swap_test.go index 91f621612d..3e95886018 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -313,7 +313,7 @@ func TestNewSwapFailure(t *testing.T) { config.dbPath = dir config.prvkey = prvKey config.backendURL = ipcEndpoint - params.PaymentThreshold, err = int256.NewUint256().Add(params.DisconnectThreshold, int256.Uint256From(1)) + params.PaymentThreshold, err = new(int256.Uint256).Add(params.DisconnectThreshold, int256.Uint256From(1)) if err != nil { t.Fatal(err) } @@ -611,7 +611,7 @@ func TestResetBalance(t *testing.T) { defer clean1() defer clean2() - testAmount, err := int256.NewUint256().Add(DefaultPaymentThreshold, int256.Uint256From(42)) + testAmount, err := new(int256.Uint256).Add(DefaultPaymentThreshold, int256.Uint256From(42)) if err != nil { t.Fatal(err) @@ -642,11 +642,11 @@ func TestResetBalance(t *testing.T) { } amount := testAmount.Value() - debitorBalance, err := int256.NewInt256().Set(amount) + debitorBalance, err := int256.NewInt256(amount) if err != nil { t.Fatal(err) } - creditorBalance, err := int256.NewInt256().Set(*new(big.Int).Mul(big.NewInt(-1), &amount)) + creditorBalance, err := int256.NewInt256(*new(big.Int).Mul(big.NewInt(-1), &amount)) if err != nil { t.Fatal(err) } @@ -720,7 +720,7 @@ func TestDebtCheques(t *testing.T) { t.Fatal(err) } - amount, err := int256.NewUint256().Mul(DefaultPaymentThreshold, int256.Uint256From(2)) + amount, err := new(int256.Uint256).Mul(DefaultPaymentThreshold, int256.Uint256From(2)) if err != nil { t.Fatal(err) } @@ -835,7 +835,7 @@ func calculateExpectedBalances(t *testing.T, swap *Swap, bookings []booking) map peerID := booking.peer.ID() peerBalance, ok := expectedBalances[peerID] if !ok { - peerBalance = int256.NewInt256() + peerBalance = new(int256.Int256) } // peer balance should only be affected if debt is being reduced or if balance is smaller than disconnect threshold if peerBalance.Cmp(swap.params.DisconnectThreshold) < 0 || booking.amount.Cmp(int256.Int256From(0)) < 0 { @@ -1297,7 +1297,7 @@ func TestSwapLogToFile(t *testing.T) { } defer clean() - testAmount, err := int256.NewUint256().Add(DefaultPaymentThreshold, int256.Uint256From(42)) + testAmount, err := new(int256.Uint256).Add(DefaultPaymentThreshold, int256.Uint256From(42)) if err != nil { t.Fatal(err) } @@ -1327,8 +1327,8 @@ func TestSwapLogToFile(t *testing.T) { } ta := testAmount.Value() - debitorAmount, err := int256.NewInt256().Set(ta) - creditorAmount, err := int256.NewInt256().Set(*new(big.Int).Mul(big.NewInt(-1), &ta)) + debitorAmount, err := int256.NewInt256(ta) + creditorAmount, err := int256.NewInt256(*new(big.Int).Mul(big.NewInt(-1), &ta)) // set balances arbitrarily if err = debitor.setBalance(debitorAmount); err != nil { t.Fatal(err) From f4a2197f7d18fc775cc165f8f5e55ee23a25b0ee Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 12 Mar 2020 16:37:06 -0300 Subject: [PATCH 48/70] int256: change param type of Equals func for Uint256 type to BigIntWrapper --- swap/int256/uint256.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 9a3ad63670..a93f69be15 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -100,7 +100,7 @@ func (u *Uint256) Cmp(v BigIntWrapper) int { } // Equals returns true if the two Uint256 structs have the same underlying values, false otherwise -func (u *Uint256) Equals(v *Uint256) bool { +func (u *Uint256) Equals(v BigIntWrapper) bool { return u.Cmp(v) == 0 } From 0cb94643afa5b70bbbd2fb86d5fdbf525bac63ea Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 19 Mar 2020 17:57:28 -0300 Subject: [PATCH 49/70] int256: change MarshalJSON to use value semantics --- swap/int256/int256.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index aa622b301d..fc0ea66739 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -110,7 +110,7 @@ func (u *Int256) String() string { // MarshalJSON implements the json.Marshaler interface // it specifies how to marshal a Int256 struct so that it can be written to disk -func (u Int256) MarshalJSON() ([]byte, error) { +func (u *Int256) MarshalJSON() ([]byte, error) { return []byte(u.value.String()), nil } From 3767d3eedfc922468d6db53392b902fdd37a8c52 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 19 Mar 2020 20:06:10 -0300 Subject: [PATCH 50/70] int256: change MarshalJSON to use value semantics --- swap/int256/uint256.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index e4d84c972b..8d4ad3c819 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -110,7 +110,7 @@ func (u *Uint256) String() string { // MarshalJSON implements the json.Marshaler interface // it specifies how to marshal a Uint256 struct so that it can be written to disk -func (u Uint256) MarshalJSON() ([]byte, error) { +func (u *Uint256) MarshalJSON() ([]byte, error) { return []byte(u.value.String()), nil } From 2aaac70c714366e06c4ea8749ae6d20d87da2108 Mon Sep 17 00:00:00 2001 From: mortelli Date: Thu, 19 Mar 2020 20:34:52 -0300 Subject: [PATCH 51/70] int256: change 2^8 int256 test case to hard-coded value --- swap/int256/int256_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index c28f2f248f..0593b7d69e 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -78,7 +78,7 @@ var int256TestCases = []testCase{ }, { name: "case 2^8", - value: new(big.Int).Exp(big.NewInt(2), big.NewInt(8), nil), + value: big.NewInt(256), expectsError: false, }, { From 6f7ba29dfbc16b0c05d5177285374af179d7a3e9 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 23 Mar 2020 16:22:29 -0300 Subject: [PATCH 52/70] int256: remove unnecessary allocations in Int256From, Uint256From, Copy and set funcs for Int256 and Uint256 structs --- swap/int256/int256.go | 6 +++--- swap/int256/uint256.go | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index fc0ea66739..858b807802 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -43,14 +43,14 @@ func NewInt256(value big.Int) (*Int256, error) { // any int64 is valid as a Int256 func Int256From(base int64) *Int256 { u := new(Int256) - u.value = *new(big.Int).SetInt64(base) + u.value.SetInt64(base) return u } // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Int256) Copy() *Int256 { v := new(Int256) - v.value = *new(big.Int).Set(&u.value) + v.value.Set(&u.value) return v } @@ -68,7 +68,7 @@ func (u *Int256) set(value big.Int) (*Int256, error) { if value.Cmp(minInt256) == -1 { return nil, fmt.Errorf("cannot set Int256 to %v as it underflows min value of %v", value, minInt256) } - u.value = *new(big.Int).Set(&value) + u.value.Set(&value) return u, nil } diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 8d4ad3c819..87f135fecf 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -43,14 +43,14 @@ func NewUint256(value big.Int) (*Uint256, error) { // any uint64 is valid as a Uint256 func Uint256From(base uint64) *Uint256 { u := new(Uint256) - u.value = *new(big.Int).SetUint64(base) + u.value.SetUint64(base) return u } // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Uint256) Copy() *Uint256 { v := new(Uint256) - v.value = *new(big.Int).Set(&u.value) + v.value.Set(&u.value) return v } @@ -68,7 +68,7 @@ func (u *Uint256) set(value big.Int) (*Uint256, error) { if value.Cmp(minUint256) == -1 { return nil, fmt.Errorf("cannot set Uint256 to %v as it underflows min value of %v", value, minUint256) } - u.value = *new(big.Int).Set(&value) + u.value.Set(&value) return u, nil } From 307d6b9b330e4895fa26b2654795fc79a7fea927 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 16:45:01 -0300 Subject: [PATCH 53/70] int256: add TestIn256ValueInjection and TestUin256ValueInjection funcs --- swap/int256/int256_test.go | 19 +++++++++++++++++++ swap/int256/uint256_test.go | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 0593b7d69e..cfb3be4a0a 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -151,6 +151,25 @@ func TestInt256Copy(t *testing.T) { } } +// TestIn256ValueInjection verifies that the underlying value for Int256 structs +// is not able to be manipulated through the getter +func TestIn256ValueInjection(t *testing.T) { + i := new(big.Int).SetInt64(-12) + v, err := NewInt256(*i) + if err != nil { + t.Fatalf("got unexpected error when creating new Int256: %v", err) + } + + vv := v.Value() + vvc := v.Value() + + vv.SetInt64(-15) + + if vvc.Cmp(&vv) == 0 { + t.Fatalf("values are equal though one should change: %v %v", vv, vvc) + } +} + // TestStore indirectly tests the marshaling and unmarshaling of a random Int256 variable func TestInt256Store(t *testing.T) { testDir, err := ioutil.TempDir("", "int256_test_store") diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index be1201ec72..46a5b72119 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -130,6 +130,25 @@ func TestUint256Copy(t *testing.T) { } } +// TestUin256ValueInjection verifies that the underlying value for Uint256 structs +// is not able to be manipulated through the getter +func TestUin256ValueInjection(t *testing.T) { + i := new(big.Int).SetUint64(44) + v, err := NewUint256(*i) + if err != nil { + t.Fatalf("got unexpected error when creating new Uint256: %v", err) + } + + vv := v.Value() + vvc := v.Value() + + vv.SetUint64(2) + + if vvc.Cmp(&vv) == 0 { + t.Fatalf("values are equal though one should change: %v %v", vv, vvc) + } +} + // TestStore indirectly tests the marshaling and unmarshaling of a random Uint256 variable func TestUint256Store(t *testing.T) { testDir, err := ioutil.TempDir("", "uint256_test_store") From 6e2f7e45b3ee08abe55d8811c1a52c0c23445c21 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 17:53:02 -0300 Subject: [PATCH 54/70] int256: change Int256 value field and funcs to user pointer semantics --- swap/int256/int256.go | 35 +++++++++++++++++++---------------- swap/int256/int256_test.go | 12 ++++++------ 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 858b807802..3a291f0d7c 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -26,7 +26,7 @@ import ( // Int256 represents an signed integer of 256 bits type Int256 struct { - value big.Int + value *big.Int } var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) @@ -34,7 +34,7 @@ var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255) // NewInt256 creates a Int256 struct with an initial underlying value of the given param // returns an error when the result falls outside of the signed 256-bit integer range -func NewInt256(value big.Int) (*Int256, error) { +func NewInt256(value *big.Int) (*Int256, error) { u := new(Int256) return u.set(value) } @@ -43,59 +43,62 @@ func NewInt256(value big.Int) (*Int256, error) { // any int64 is valid as a Int256 func Int256From(base int64) *Int256 { u := new(Int256) - u.value.SetInt64(base) + u.value = new(big.Int).SetInt64(base) return u } // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Int256) Copy() *Int256 { v := new(Int256) - v.value.Set(&u.value) + v.value = new(big.Int).Set(u.value) return v } // Value returns the underlying private value for a Int256 struct -func (u *Int256) Value() big.Int { - return u.value +func (u *Int256) Value() *big.Int { + return new(big.Int).Set(u.value) } // set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the signed 256-bit integer range -func (u *Int256) set(value big.Int) (*Int256, error) { +func (u *Int256) set(value *big.Int) (*Int256, error) { if value.Cmp(maxInt256) == 1 { return nil, fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) } if value.Cmp(minInt256) == -1 { return nil, fmt.Errorf("cannot set Int256 to %v as it underflows min value of %v", value, minInt256) } - u.value.Set(&value) + if u.value == nil { + u.value = new(big.Int) + } + u.value.Set(value) return u, nil } // Add sets u to augend + addend and returns u as the sum // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Add(augend, addend *Int256) (*Int256, error) { - sum := new(big.Int).Add(&augend.value, &addend.value) - return u.set(*sum) + sum := new(big.Int).Add(augend.value, addend.value) + return u.set(sum) } // Sub sets u to minuend - subtrahend and returns u as the difference // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Sub(minuend, subtrahend *Int256) (*Int256, error) { - difference := new(big.Int).Sub(&minuend.value, &subtrahend.value) - return u.set(*difference) + difference := new(big.Int).Sub(minuend.value, subtrahend.value) + return u.set(difference) } // Mul sets u to multiplicand * multiplier and returns u as the product // returns an error when the result falls outside of the signed 256-bit integer range func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { - product := new(big.Int).Mul(&multiplicand.value, &multiplier.value) - return u.set(*product) + product := new(big.Int).Mul(multiplicand.value, multiplier.value) + return u.set(product) } // cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field func (u *Int256) cmp(v *Int256) int { - return u.value.Cmp(&v.value) + return u.value.Cmp(v.value) } // Equals returns true if the two Int256 structs have the same underlying values, false otherwise @@ -126,7 +129,7 @@ func (u *Int256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - _, err := u.set(value) + _, err := u.set(&value) return err } diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index cfb3be4a0a..508457853f 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -107,7 +107,7 @@ var int256TestCases = []testCase{ func TestInt256Set(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewInt256(*tc.value) + result, err := NewInt256(tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Int256, but got none") } @@ -116,7 +116,7 @@ func TestInt256Set(t *testing.T) { t.Fatalf("got unexpected error when creating new Int256: %v", err) } resultValue := result.Value() - if (&resultValue).Cmp(tc.value) != 0 { + if resultValue.Cmp(tc.value) != 0 { t.Fatalf("expected value of %v, got %v instead", tc.value, result.value) } } @@ -128,7 +128,7 @@ func TestInt256Set(t *testing.T) { func TestInt256Copy(t *testing.T) { // pick test value i := new(big.Int).Exp(big.NewInt(-2), big.NewInt(128), nil) // -2^128 - v, err := NewInt256(*i) + v, err := NewInt256(i) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } @@ -155,7 +155,7 @@ func TestInt256Copy(t *testing.T) { // is not able to be manipulated through the getter func TestIn256ValueInjection(t *testing.T) { i := new(big.Int).SetInt64(-12) - v, err := NewInt256(*i) + v, err := NewInt256(i) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } @@ -165,7 +165,7 @@ func TestIn256ValueInjection(t *testing.T) { vv.SetInt64(-15) - if vvc.Cmp(&vv) == 0 { + if vvc.Cmp(vv) == 0 { t.Fatalf("values are equal though one should change: %v %v", vv, vvc) } } @@ -186,7 +186,7 @@ func TestInt256Store(t *testing.T) { for _, tc := range int256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewInt256(*tc.value) + r, err := NewInt256(tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Int256: %v", err) } From 7ad6424dd0a08c20eeccc8321cbd9defd39bf982 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 20:57:00 -0300 Subject: [PATCH 55/70] int256: change Uint256 value field and funcs to user pointer semantics --- swap/int256/uint256.go | 35 +++++++++++++++++++---------------- swap/int256/uint256_test.go | 4 ++-- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 87f135fecf..11abc1384a 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -26,7 +26,7 @@ import ( // Uint256 represents an unsigned integer of 256 bits type Uint256 struct { - value big.Int + value *big.Int } var minUint256 = big.NewInt(0) @@ -34,7 +34,7 @@ var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256 // NewUint256 creates a Uint256 struct with an initial underlying value of the given param // returns an error when the result falls outside of the unsigned 256-bit integer range -func NewUint256(value big.Int) (*Uint256, error) { +func NewUint256(value *big.Int) (*Uint256, error) { u := new(Uint256) return u.set(value) } @@ -43,59 +43,62 @@ func NewUint256(value big.Int) (*Uint256, error) { // any uint64 is valid as a Uint256 func Uint256From(base uint64) *Uint256 { u := new(Uint256) - u.value.SetUint64(base) + u.value = new(big.Int).SetUint64(base) return u } // Copy creates and returns a new Int256 instance, with its underlying value set matching the receiver func (u *Uint256) Copy() *Uint256 { v := new(Uint256) - v.value.Set(&u.value) + v.value = new(big.Int).Set(u.value) return v } // Value returns the underlying private value for a Uint256 struct -func (u *Uint256) Value() big.Int { - return u.value +func (u *Uint256) Value() *big.Int { + return new(big.Int).Set(u.value) } // set assigns the underlying value of the given Uint256 param to u, and returns the modified receiver struct // returns an error when the result falls outside of the unsigned 256-bit integer range -func (u *Uint256) set(value big.Int) (*Uint256, error) { +func (u *Uint256) set(value *big.Int) (*Uint256, error) { if value.Cmp(maxUint256) == 1 { return nil, fmt.Errorf("cannot set Uint256 to %v as it overflows max value of %v", value, maxUint256) } if value.Cmp(minUint256) == -1 { return nil, fmt.Errorf("cannot set Uint256 to %v as it underflows min value of %v", value, minUint256) } - u.value.Set(&value) + if u.value == nil { + u.value = new(big.Int) + } + u.value.Set(value) return u, nil } // Add sets u to augend + addend and returns u as the sum // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Add(augend, addend *Uint256) (*Uint256, error) { - sum := new(big.Int).Add(&augend.value, &addend.value) - return u.set(*sum) + sum := new(big.Int).Add(augend.value, addend.value) + return u.set(sum) } // Sub sets u to minuend - subtrahend and returns u as the difference // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Sub(minuend, subtrahend *Uint256) (*Uint256, error) { - difference := new(big.Int).Sub(&minuend.value, &subtrahend.value) - return u.set(*difference) + difference := new(big.Int).Sub(minuend.value, subtrahend.value) + return u.set(difference) } // Mul sets u to multiplicand * multiplier and returns u as the product // returns an error when the result falls outside of the unsigned 256-bit integer range func (u *Uint256) Mul(multiplicand, multiplier *Uint256) (*Uint256, error) { - product := new(big.Int).Mul(&multiplicand.value, &multiplier.value) - return u.set(*product) + product := new(big.Int).Mul(multiplicand.value, multiplier.value) + return u.set(product) } // Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field func (u *Uint256) Cmp(v *Uint256) int { - return u.value.Cmp(&v.value) + return u.value.Cmp(v.value) } // Equals returns true if the two Uint256 structs have the same underlying values, false otherwise @@ -126,7 +129,7 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - _, err := u.set(value) + _, err := u.set(&value) return err } diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 46a5b72119..c3baabba61 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -95,7 +95,7 @@ func TestUint256Set(t *testing.T) { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } resultValue := result.Value() - if (&resultValue).Cmp(tc.value) != 0 { + if resultValue.Cmp(tc.value) != 0 { t.Fatalf("expected value of %v, got %v instead", tc.value, result.value) } } @@ -144,7 +144,7 @@ func TestUin256ValueInjection(t *testing.T) { vv.SetUint64(2) - if vvc.Cmp(&vv) == 0 { + if vvc.Cmp(vv) == 0 { t.Fatalf("values are equal though one should change: %v %v", vv, vvc) } } From 208ef2fb18686cc081644ee092a91b643bb3dd65 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 21:00:46 -0300 Subject: [PATCH 56/70] int256: fix Uint256 tests to work with pointer semantics --- swap/int256/uint256_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index c3baabba61..94a3382310 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -86,7 +86,7 @@ var uint256TestCases = []testCase{ func TestUint256Set(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { - result, err := NewUint256(*tc.value) + result, err := NewUint256(tc.value) if tc.expectsError && err == nil { t.Fatalf("expected error when creating new Uint256, but got none") } @@ -107,7 +107,7 @@ func TestUint256Set(t *testing.T) { func TestUint256Copy(t *testing.T) { // pick test value i := new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil) // 2^128 - v, err := NewUint256(*i) + v, err := NewUint256(i) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } @@ -134,7 +134,7 @@ func TestUint256Copy(t *testing.T) { // is not able to be manipulated through the getter func TestUin256ValueInjection(t *testing.T) { i := new(big.Int).SetUint64(44) - v, err := NewUint256(*i) + v, err := NewUint256(i) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } @@ -165,7 +165,7 @@ func TestUint256Store(t *testing.T) { for _, tc := range uint256TestCases { t.Run(tc.name, func(t *testing.T) { if !tc.expectsError { - r, err := NewUint256(*tc.value) + r, err := NewUint256(tc.value) if err != nil { t.Fatalf("got unexpected error when creating new Uint256: %v", err) } From 23dad457cd065e32fbfdb14c35bab5cf2d52cf8f Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 21:09:01 -0300 Subject: [PATCH 57/70] swap, contracts/swap: fix swap code to work with new int256 pointer semantics --- contracts/swap/swap.go | 2 +- swap/api.go | 4 ++-- swap/cashout.go | 4 ++-- swap/cheque.go | 3 +-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/contracts/swap/swap.go b/contracts/swap/swap.go index 8a096ba34a..a42a1c204b 100644 --- a/contracts/swap/swap.go +++ b/contracts/swap/swap.go @@ -134,7 +134,7 @@ func (s simpleContract) Deposit(auth *bind.TransactOpts, amount *big.Int) (*type func (s simpleContract) CashChequeBeneficiaryStart(opts *bind.TransactOpts, beneficiary common.Address, cumulativePayout *int256.Uint256, ownerSig []byte) (*types.Transaction, error) { payout := cumulativePayout.Value() // send a copy of cumulativePayout to instance as it modifies the supplied big int internally - tx, err := s.instance.CashChequeBeneficiary(opts, beneficiary, big.NewInt(0).Set(&payout), ownerSig) + tx, err := s.instance.CashChequeBeneficiary(opts, beneficiary, big.NewInt(0).Set(payout), ownerSig) if err != nil { return nil, err } diff --git a/swap/api.go b/swap/api.go index c016e8f285..bb864cfd74 100644 --- a/swap/api.go +++ b/swap/api.go @@ -80,7 +80,7 @@ func (s *Swap) AvailableBalance() (*int256.Uint256, error) { continue } cumulativePayout := sentCheque.ChequeParams.CumulativePayout.Value() - sentChequesWorth.Add(sentChequesWorth, &cumulativePayout) + sentChequesWorth.Add(sentChequesWorth, cumulativePayout) paidOut, err := s.contract.PaidOut(nil, sentCheque.ChequeParams.Beneficiary) if err != nil { return nil, err @@ -91,7 +91,7 @@ func (s *Swap) AvailableBalance() (*int256.Uint256, error) { totalChequesWorth := new(big.Int).Sub(cashedChequesWorth, sentChequesWorth) tentativeLiquidBalance := new(big.Int).Add(contractLiquidBalance, totalChequesWorth) - return int256.NewUint256(*tentativeLiquidBalance) + return int256.NewUint256(tentativeLiquidBalance) } // PeerBalance returns the balance for a given peer diff --git a/swap/cashout.go b/swap/cashout.go index c860022176..03d0c0fff3 100644 --- a/swap/cashout.go +++ b/swap/cashout.go @@ -97,7 +97,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - paidOut, err := int256.NewUint256(*po) + paidOut, err := int256.NewUint256(po) if err != nil { return nil, nil, err } @@ -107,7 +107,7 @@ func (c *CashoutProcessor) estimatePayout(ctx context.Context, cheque *Cheque) ( return nil, nil, err } - gasPrice, err := int256.NewUint256(*gp) + gasPrice, err := int256.NewUint256(gp) if err != nil { return nil, nil, err } diff --git a/swap/cheque.go b/swap/cheque.go index eb0737cfa9..7760a88db7 100644 --- a/swap/cheque.go +++ b/swap/cheque.go @@ -31,8 +31,7 @@ func (cheque *ChequeParams) encodeForSignature() []byte { cumulativePayoutBytes := make([]byte, 32) // we need to write the last 8 bytes as we write a uint64 into a 32-byte array // encoded in BigEndian because EVM uses BigEndian encoding - cumulativePayout := cheque.CumulativePayout.Value() - chequePayoutBytes := (&cumulativePayout).Bytes() + chequePayoutBytes := cheque.CumulativePayout.Value().Bytes() copy(cumulativePayoutBytes[32-len(chequePayoutBytes):], chequePayoutBytes) // construct the actual cheque From 82549c0ace36967229dbe6a9a6ce300a95a1685c Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 22:28:37 -0300 Subject: [PATCH 58/70] swap: fix swap tests to work with new int256 pointer semantics --- swap/cashout_test.go | 4 ++-- swap/common_test.go | 4 ++-- swap/swap_test.go | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/swap/cashout_test.go b/swap/cashout_test.go index d00cf5c907..cf847c5fc1 100644 --- a/swap/cashout_test.go +++ b/swap/cashout_test.go @@ -74,7 +74,7 @@ func TestContractIntegration(t *testing.T) { if err != nil { t.Fatal(err) } - paidOut, err := int256.NewUint256(*result) + paidOut, err := int256.NewUint256(result) if err != nil { t.Fatal(err) } @@ -150,7 +150,7 @@ func TestCashCheque(t *testing.T) { } cumulativePayout := testCheque.CumulativePayout.Value() - if paidOut.Cmp(&cumulativePayout) != 0 { + if paidOut.Cmp(cumulativePayout) != 0 { t.Fatalf("paidOut does not equal the CumulativePayout: paidOut=%v expected=%v", paidOut, testCheque.CumulativePayout) } } diff --git a/swap/common_test.go b/swap/common_test.go index d6efae94f1..ef3a36f3bc 100644 --- a/swap/common_test.go +++ b/swap/common_test.go @@ -180,7 +180,7 @@ func newSignedTestCheque(testChequeContract common.Address, beneficiaryAddress c CumulativePayout: cumulativePayout, Beneficiary: beneficiaryAddress, }, - Honey: (&cp).Uint64(), + Honey: cp.Uint64(), } sig, err := cheque.Sign(signingKey) @@ -264,7 +264,7 @@ func testDeployWithPrivateKey(ctx context.Context, backend chain.Backend, privat } deposit := depositAmount.Value() - tx, err := token.Mint(bind.NewKeyedTransactor(ownerKey), contract.ContractParams().ContractAddress, &deposit) + tx, err := token.Mint(bind.NewKeyedTransactor(ownerKey), contract.ContractParams().ContractAddress, deposit) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index a3b94f985c..b562a0c35f 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -1467,7 +1467,7 @@ func TestAvailableBalance(t *testing.T) { opts := bind.NewKeyedTransactor(swap.owner.privateKey) opts.Context = context.TODO() - rec, err := swap.contract.Withdraw(opts, &withdraw) + rec, err := swap.contract.Withdraw(opts, withdraw) if err != nil { t.Fatal(err) } From 8ef80df91b82dafb75001d0350e04d803b8def3b Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 22:39:12 -0300 Subject: [PATCH 59/70] int256: make sure all big.Int Set calls are done from pointer receivers rather than values --- swap/int256/int256.go | 2 +- swap/int256/int256_test.go | 2 +- swap/int256/uint256.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 3a291f0d7c..f60a8c15d2 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -125,7 +125,7 @@ func (u *Int256) UnmarshalJSON(b []byte) error { } var value big.Int - _, ok := value.SetString(string(b), 10) + _, ok := (&value).SetString(string(b), 10) if !ok { return fmt.Errorf("not a valid integer value: %s", b) } diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 508457853f..69f1d54224 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -163,7 +163,7 @@ func TestIn256ValueInjection(t *testing.T) { vv := v.Value() vvc := v.Value() - vv.SetInt64(-15) + vv.SetInt64(15) if vvc.Cmp(vv) == 0 { t.Fatalf("values are equal though one should change: %v %v", vv, vvc) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 11abc1384a..37de67c3d2 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -125,7 +125,7 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { } var value big.Int - _, ok := value.SetString(string(b), 10) + _, ok := (&value).SetString(string(b), 10) if !ok { return fmt.Errorf("not a valid integer value: %s", b) } From 82067166b542af90c4d9e7b334024a24b6375e70 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 23:30:25 -0300 Subject: [PATCH 60/70] int256: extract checkUint256Bounds and checkInt256Bounds funcs, fix error in Int256 and Uint256 DecodeRLP funcs, iterate func comments --- swap/int256/int256.go | 35 +++++++++++++++++++++++------------ swap/int256/uint256.go | 39 +++++++++++++++++++++++++++------------ 2 files changed, 50 insertions(+), 24 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index f60a8c15d2..c00780449f 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -60,13 +60,10 @@ func (u *Int256) Value() *big.Int { } // set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct -// returns an error when the result falls outside of the signed 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Int256) set(value *big.Int) (*Int256, error) { - if value.Cmp(maxInt256) == 1 { - return nil, fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) - } - if value.Cmp(minInt256) == -1 { - return nil, fmt.Errorf("cannot set Int256 to %v as it underflows min value of %v", value, minInt256) + if err := checkUint256Bounds(value); err != nil { + return nil, err } if u.value == nil { u.value = new(big.Int) @@ -75,22 +72,34 @@ func (u *Int256) set(value *big.Int) (*Int256, error) { return u, nil } +// checkInt256Bounds returns an error when the given value falls outside of the signed 256-bit integer range +// returns nil otherwise +func checkInt256Bounds(value *big.Int) error { + if value.Cmp(maxInt256) == 1 { + return fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) + } + if value.Cmp(minInt256) == -1 { + return fmt.Errorf("cannot set Int256 to %v as it underflows min value of %v", value, minInt256) + } + return nil +} + // Add sets u to augend + addend and returns u as the sum -// returns an error when the result falls outside of the signed 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Int256) Add(augend, addend *Int256) (*Int256, error) { sum := new(big.Int).Add(augend.value, addend.value) return u.set(sum) } // Sub sets u to minuend - subtrahend and returns u as the difference -// returns an error when the result falls outside of the signed 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Int256) Sub(minuend, subtrahend *Int256) (*Int256, error) { difference := new(big.Int).Sub(minuend.value, subtrahend.value) return u.set(difference) } // Mul sets u to multiplicand * multiplier and returns u as the product -// returns an error when the result falls outside of the signed 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { product := new(big.Int).Mul(multiplicand.value, multiplier.value) return u.set(product) @@ -143,8 +152,10 @@ func (u *Int256) EncodeRLP(w io.Writer) error { // it makes sure the value field is decoded even though it is private func (u *Int256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { - return nil + return err } - _, err := u.set(u.value) - return err + if err := checkInt256Bounds(u.value); err != nil { + return err + } + return nil } diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 37de67c3d2..835951f59c 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -60,13 +60,10 @@ func (u *Uint256) Value() *big.Int { } // set assigns the underlying value of the given Uint256 param to u, and returns the modified receiver struct -// returns an error when the result falls outside of the unsigned 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Uint256) set(value *big.Int) (*Uint256, error) { - if value.Cmp(maxUint256) == 1 { - return nil, fmt.Errorf("cannot set Uint256 to %v as it overflows max value of %v", value, maxUint256) - } - if value.Cmp(minUint256) == -1 { - return nil, fmt.Errorf("cannot set Uint256 to %v as it underflows min value of %v", value, minUint256) + if err := checkUint256Bounds(value); err != nil { + return nil, err } if u.value == nil { u.value = new(big.Int) @@ -75,22 +72,34 @@ func (u *Uint256) set(value *big.Int) (*Uint256, error) { return u, nil } +// checkUint256NBounds returns an error when the given value falls outside of the unsigned 256-bit integer range +// returns nil otherwise +func checkUint256Bounds(value *big.Int) error { + if value.Cmp(maxUint256) == 1 { + return fmt.Errorf("cannot set Uint256 to %v as it overflows max value of %v", value, maxUint256) + } + if value.Cmp(minUint256) == -1 { + return fmt.Errorf("cannot set Uint256 to %v as it underflows min value of %v", value, minUint256) + } + return nil +} + // Add sets u to augend + addend and returns u as the sum -// returns an error when the result falls outside of the unsigned 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Uint256) Add(augend, addend *Uint256) (*Uint256, error) { sum := new(big.Int).Add(augend.value, addend.value) return u.set(sum) } // Sub sets u to minuend - subtrahend and returns u as the difference -// returns an error when the result falls outside of the unsigned 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Uint256) Sub(minuend, subtrahend *Uint256) (*Uint256, error) { difference := new(big.Int).Sub(minuend.value, subtrahend.value) return u.set(difference) } // Mul sets u to multiplicand * multiplier and returns u as the product -// returns an error when the result falls outside of the unsigned 256-bit integer range +// returns an error when the value cannot be correctly set func (u *Uint256) Mul(multiplicand, multiplier *Uint256) (*Uint256, error) { product := new(big.Int).Mul(multiplicand.value, multiplier.value) return u.set(product) @@ -129,6 +138,10 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } + + if err := checkUint256Bounds(&value); err != nil { + return err + } _, err := u.set(&value) return err } @@ -143,8 +156,10 @@ func (u *Uint256) EncodeRLP(w io.Writer) error { // it makes sure the value field is decoded even though it is private func (u *Uint256) DecodeRLP(s *rlp.Stream) error { if err := s.Decode(&u.value); err != nil { - return nil + return err } - _, err := u.set(u.value) - return err + if err := checkUint256Bounds(u.value); err != nil { + return err + } + return nil } From ddbe749d64df45b9f20b09f16a064276c9e09989 Mon Sep 17 00:00:00 2001 From: mortelli Date: Tue, 24 Mar 2020 23:36:43 -0300 Subject: [PATCH 61/70] int256: fix wrong call of boundary-checking in `Int256`'s `set` func --- swap/int256/int256.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index c00780449f..e112959ae6 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -62,7 +62,7 @@ func (u *Int256) Value() *big.Int { // set assigns the underlying value of the given Int256 param to u, and returns the modified receiver struct // returns an error when the value cannot be correctly set func (u *Int256) set(value *big.Int) (*Int256, error) { - if err := checkUint256Bounds(value); err != nil { + if err := checkInt256Bounds(value); err != nil { return nil, err } if u.value == nil { From 14181247a6d402a9b1cf41f444f48bc12c2633e7 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 25 Mar 2020 10:48:59 -0300 Subject: [PATCH 62/70] int256: update BigIntWrapper interface to use pointer semantics --- swap/int256/int256.go | 6 +++--- swap/int256/uint256.go | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 8750af16cb..c84cfc17c6 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -31,7 +31,7 @@ type Int256 struct { // BigIntWrapper represents a struct with an underlying big.Int value type BigIntWrapper interface { - Value() big.Int + Value() *big.Int } var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)) // -(2^255) @@ -111,8 +111,8 @@ func (u *Int256) Mul(multiplicand, multiplier *Int256) (*Int256, error) { } // cmp calls the underlying Cmp method for the big.Int stored in a Int256 struct as its value field -func (u *Int256) Cmp(v *BigIntWrapper) int { - return u.value.Cmp(v.value) +func (u *Int256) Cmp(v BigIntWrapper) int { + return u.value.Cmp(v.Value()) } // Equals returns true if the two Int256 structs have the same underlying values, false otherwise diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 185319c23c..6bfde47fa0 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -106,8 +106,8 @@ func (u *Uint256) Mul(multiplicand, multiplier *Uint256) (*Uint256, error) { } // Cmp calls the underlying Cmp method for the big.Int stored in a Uint256 struct as its value field -func (u *Uint256) Cmp(v *BigIntWrapper) int { - return u.value.Cmp(v.value) +func (u *Uint256) Cmp(v BigIntWrapper) int { + return u.value.Cmp(v.Value()) } // Equals returns true if the two Uint256 structs have the same underlying values, false otherwise From e591affc4c9b60f2e7f9fdc453c9991088695e78 Mon Sep 17 00:00:00 2001 From: mortelli Date: Wed, 25 Mar 2020 12:43:54 -0300 Subject: [PATCH 63/70] int256: add nil value checking to checkInt256Bounds and checkUint256Bounds funcs --- swap/int256/int256.go | 5 ++++- swap/int256/int256_test.go | 6 ++++++ swap/int256/uint256.go | 5 ++++- swap/int256/uint256_test.go | 6 ++++++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index e112959ae6..d6ec2aa94c 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -72,9 +72,12 @@ func (u *Int256) set(value *big.Int) (*Int256, error) { return u, nil } -// checkInt256Bounds returns an error when the given value falls outside of the signed 256-bit integer range +// checkInt256Bounds returns an error when the given value falls outside of the signed 256-bit integer range or is nil // returns nil otherwise func checkInt256Bounds(value *big.Int) error { + if value == nil { + return fmt.Errorf("cannot set Int256 to a nil value") + } if value.Cmp(maxInt256) == 1 { return fmt.Errorf("cannot set Int256 to %v as it overflows max value of %v", value, maxInt256) } diff --git a/swap/int256/int256_test.go b/swap/int256/int256_test.go index 69f1d54224..8eb38e2e16 100644 --- a/swap/int256/int256_test.go +++ b/swap/int256/int256_test.go @@ -101,6 +101,12 @@ var int256TestCases = []testCase{ value: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, + // nil case + { + name: "case nil", + value: nil, + expectsError: true, + }, } // TestSet tests the creation of valid and invalid Int256 structs by calling the Set function diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 835951f59c..ea27b60034 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -72,9 +72,12 @@ func (u *Uint256) set(value *big.Int) (*Uint256, error) { return u, nil } -// checkUint256NBounds returns an error when the given value falls outside of the unsigned 256-bit integer range +// checkUint256NBounds returns an error when the given value falls outside of the unsigned 256-bit integer range or is nil // returns nil otherwise func checkUint256Bounds(value *big.Int) error { + if value == nil { + return fmt.Errorf("cannot set Uint256 to a nil value") + } if value.Cmp(maxUint256) == 1 { return fmt.Errorf("cannot set Uint256 to %v as it overflows max value of %v", value, maxUint256) } diff --git a/swap/int256/uint256_test.go b/swap/int256/uint256_test.go index 94a3382310..4d8c8217ed 100644 --- a/swap/int256/uint256_test.go +++ b/swap/int256/uint256_test.go @@ -80,6 +80,12 @@ var uint256TestCases = []testCase{ value: new(big.Int).Exp(big.NewInt(2), big.NewInt(512), nil), expectsError: true, }, + // nil case + { + name: "case nil", + value: nil, + expectsError: true, + }, } // TestSet tests the creation of valid and invalid Uint256 structs by calling the Set function From 138fcbe983b734d8fd28a5a5c9b9f00f5ec25170 Mon Sep 17 00:00:00 2001 From: mortelli Date: Sun, 29 Mar 2020 17:10:05 -0300 Subject: [PATCH 64/70] int256: quote and unquote Int256 and Uint256 values in marshaling/unmarshaling functions to prevent json number overflow --- swap/int256/int256.go | 13 ++++++++++--- swap/int256/uint256.go | 15 +++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index d6ec2aa94c..a3e845ff8e 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -20,6 +20,7 @@ import ( "fmt" "io" "math/big" + "strconv" "github.com/ethereum/go-ethereum/rlp" ) @@ -126,7 +127,8 @@ func (u *Int256) String() string { // MarshalJSON implements the json.Marshaler interface // it specifies how to marshal a Int256 struct so that it can be written to disk func (u *Int256) MarshalJSON() ([]byte, error) { - return []byte(u.value.String()), nil + // number is wrapped in quotes to prevent json number overflowing + return []byte(strconv.Quote(u.value.String())), nil } // UnmarshalJSON implements the json.Unmarshaler interface @@ -137,11 +139,16 @@ func (u *Int256) UnmarshalJSON(b []byte) error { } var value big.Int - _, ok := (&value).SetString(string(b), 10) + // value string must be unquoted due to marshaling + strValue, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + _, ok := (&value).SetString(strValue, 10) if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - _, err := u.set(&value) + _, err = u.set(&value) return err } diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index ea27b60034..6e372bdd55 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -20,6 +20,7 @@ import ( "fmt" "io" "math/big" + "strconv" "github.com/ethereum/go-ethereum/rlp" ) @@ -33,7 +34,7 @@ var minUint256 = big.NewInt(0) var maxUint256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(256), nil), big.NewInt(1)) // 2^256 - 1 // NewUint256 creates a Uint256 struct with an initial underlying value of the given param -// returns an error when the result falls outside of the unsigned 256-bit integer range +// returns an error when the value cannot be correctly set func NewUint256(value *big.Int) (*Uint256, error) { u := new(Uint256) return u.set(value) @@ -126,7 +127,8 @@ func (u *Uint256) String() string { // MarshalJSON implements the json.Marshaler interface // it specifies how to marshal a Uint256 struct so that it can be written to disk func (u *Uint256) MarshalJSON() ([]byte, error) { - return []byte(u.value.String()), nil + // number is wrapped in quotes to prevent json number overflowing + return []byte(strconv.Quote(u.value.String())), nil } // UnmarshalJSON implements the json.Unmarshaler interface @@ -137,7 +139,12 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { } var value big.Int - _, ok := (&value).SetString(string(b), 10) + // value string must be unquoted due to marshaling + strValue, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + _, ok := (&value).SetString(strValue, 10) if !ok { return fmt.Errorf("not a valid integer value: %s", b) } @@ -145,7 +152,7 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { if err := checkUint256Bounds(&value); err != nil { return err } - _, err := u.set(&value) + _, err = u.set(&value) return err } From f7bb5c246b480687c560213dbc49c81eafe0218b Mon Sep 17 00:00:00 2001 From: mortelli Date: Sun, 29 Mar 2020 17:23:47 -0300 Subject: [PATCH 65/70] int256: disallow nil values when unmarshaling Int256 and Uint256 structs --- swap/int256/int256.go | 6 +----- swap/int256/uint256.go | 4 ---- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index a3e845ff8e..1f3acff987 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -34,7 +34,7 @@ var minInt256 = new(big.Int).Mul(big.NewInt(-1), new(big.Int).Exp(big.NewInt(2), var maxInt256 = new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil), big.NewInt(1)) // 2^255 - 1 // NewInt256 creates a Int256 struct with an initial underlying value of the given param -// returns an error when the result falls outside of the signed 256-bit integer range +// returns an error when the value cannot be correctly set func NewInt256(value *big.Int) (*Int256, error) { u := new(Int256) return u.set(value) @@ -134,10 +134,6 @@ func (u *Int256) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the json.Unmarshaler interface // it specifies how to unmarshal a Int256 struct so that it can be reconstructed from disk func (u *Int256) UnmarshalJSON(b []byte) error { - if string(b) == "null" { - return nil - } - var value big.Int // value string must be unquoted due to marshaling strValue, err := strconv.Unquote(string(b)) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 6e372bdd55..7ef4dea590 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -134,10 +134,6 @@ func (u *Uint256) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the json.Unmarshaler interface // it specifies how to unmarshal a Uint256 struct so that it can be reconstructed from disk func (u *Uint256) UnmarshalJSON(b []byte) error { - if string(b) == "null" { - return nil - } - var value big.Int // value string must be unquoted due to marshaling strValue, err := strconv.Unquote(string(b)) From 48b4707d49f198cec6910a3894c9ebe01816af5d Mon Sep 17 00:00:00 2001 From: mortelli Date: Sun, 29 Mar 2020 18:08:23 -0300 Subject: [PATCH 66/70] int256: remove unneeded code in Uint256 UnmarshalJSON func --- swap/int256/uint256.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 7ef4dea590..d341c6b6dd 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -144,10 +144,6 @@ func (u *Uint256) UnmarshalJSON(b []byte) error { if !ok { return fmt.Errorf("not a valid integer value: %s", b) } - - if err := checkUint256Bounds(&value); err != nil { - return err - } _, err = u.set(&value) return err } From 2d0837f75562938f30f81b2ad1be91f73dbc801e Mon Sep 17 00:00:00 2001 From: mortelli Date: Sun, 29 Mar 2020 19:03:03 -0300 Subject: [PATCH 67/70] main: simplify TestConfigCmdLineOverrides thresholds printing --- cmd/swarm/config_test.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index 1f25504ff7..fe0b19c08a 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -24,7 +24,6 @@ import ( "net" "os" "os/exec" - "strconv" "testing" "time" @@ -253,8 +252,8 @@ func TestConfigCmdLineOverrides(t *testing.T) { fmt.Sprintf("--%s", utils.DataDirFlag.Name), dir, fmt.Sprintf("--%s", utils.IPCPathFlag.Name), conf.IPCPath, "--verbosity", fmt.Sprintf("%d", *testutil.Loglevel), - fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), strconv.FormatUint(paymentThreshold.Uint64(), 10), - fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), strconv.FormatUint(disconnectThreshold.Uint64(), 10), + fmt.Sprintf("--%s", SwarmSwapPaymentThresholdFlag.Name), paymentThreshold.String(), + fmt.Sprintf("--%s", SwarmSwapDisconnectThresholdFlag.Name), disconnectThreshold.String(), fmt.Sprintf("--%s", SwarmEnablePinningFlag.Name), } From b57d27a75727e7cc913e1712b73040218768e28a Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 30 Mar 2020 16:09:45 -0300 Subject: [PATCH 68/70] int256: extend Int256 and Uint256 Value funcs to return nil if possible, fix swap logic and tests to work with new pointer semantics in int256 --- swap/int256/int256.go | 4 ++++ swap/int256/uint256.go | 4 ++++ swap/peer.go | 2 +- swap/protocol_test.go | 6 +++--- swap/simulations_test.go | 4 ++-- swap/swap.go | 4 ++-- swap/swap_test.go | 10 +++++----- 7 files changed, 21 insertions(+), 13 deletions(-) diff --git a/swap/int256/int256.go b/swap/int256/int256.go index 6ae45d8503..1199676723 100644 --- a/swap/int256/int256.go +++ b/swap/int256/int256.go @@ -62,6 +62,10 @@ func (u *Int256) Copy() *Int256 { // Value returns the underlying private value for a Int256 struct func (u *Int256) Value() *big.Int { + if u.value == nil { + return nil + } + // clone the value to avoid external modification return new(big.Int).Set(u.value) } diff --git a/swap/int256/uint256.go b/swap/int256/uint256.go index 768726615e..ed79cefa12 100644 --- a/swap/int256/uint256.go +++ b/swap/int256/uint256.go @@ -57,6 +57,10 @@ func (u *Uint256) Copy() *Uint256 { // Value returns the underlying private value for a Uint256 struct func (u *Uint256) Value() *big.Int { + if u.value == nil { + return nil + } + // clone the value to avoid external modification return new(big.Int).Set(u.value) } diff --git a/swap/peer.go b/swap/peer.go index 446f9b219b..f09766caa6 100644 --- a/swap/peer.go +++ b/swap/peer.go @@ -164,7 +164,7 @@ func (p *Peer) createCheque() (*Cheque, error) { } // the balance should be negative here, we take the absolute value: b := p.getBalance().Value() - balance := new(big.Int).Mul(&b, big.NewInt(-1)) + balance := new(big.Int).Mul(b, big.NewInt(-1)) honey := balance.Uint64() oraclePrice, err := p.swap.honeyPriceOracle.GetPrice(honey) diff --git a/swap/protocol_test.go b/swap/protocol_test.go index 39dc85a11c..1f079f68ce 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -405,7 +405,7 @@ func TestTriggerPaymentThreshold(t *testing.T) { } ea := expectedAmount.Value() - if pending.Honey != (&ea).Uint64() { + if pending.Honey != ea.Uint64() { t.Fatalf("Expected cheque honey to be %v, but is %v", expectedAmount, pending.Honey) } @@ -614,7 +614,7 @@ func TestSwapRPC(t *testing.T) { log.Debug("servicenode balance", "balance", balance) // ...thus balance should be empty - if !balance.Equals(new(int256.Int256)) { + if balance.Value() != nil { t.Fatalf("Expected balance to be empty but it is %v", balance) } @@ -663,7 +663,7 @@ func TestSwapRPC(t *testing.T) { } log.Debug("received balances", "allBalances", allBalances) - sum := new(int256.Int256) + sum := int256.Int256From(0) for _, v := range allBalances { sum.Add(sum, v) } diff --git a/swap/simulations_test.go b/swap/simulations_test.go index c1a60d4386..ca0f9de173 100644 --- a/swap/simulations_test.go +++ b/swap/simulations_test.go @@ -386,7 +386,7 @@ func TestMultiChequeSimulation(t *testing.T) { } mp := new(big.Int).SetUint64(msgPrice) - price, err := int256.NewInt256(*mp) + price, err := int256.NewInt256(mp) if err != nil { t.Fatal(err) } @@ -409,7 +409,7 @@ func TestMultiChequeSimulation(t *testing.T) { t.Fatal(err) } b := balanceAfterMessage.Value() - expectedPayout += (&b).Uint64() + expectedPayout += b.Uint64() } lastCount++ diff --git a/swap/swap.go b/swap/swap.go index b302e342d7..27e610ae62 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -494,7 +494,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, } chequeHoney := new(big.Int).SetUint64(cheque.Honey) - honey, err := int256.NewInt256(*chequeHoney) + honey, err := int256.NewInt256(chequeHoney) if err != nil { return nil, err } @@ -506,7 +506,7 @@ func (s *Swap) processAndVerifyCheque(cheque *Cheque, p *Peer) (*int256.Uint256, } debtTolerance := big.NewInt(-int64(ChequeDebtTolerance)) - tolerance, err := int256.NewInt256(*debtTolerance) + tolerance, err := int256.NewInt256(debtTolerance) if err != nil { return nil, err } diff --git a/swap/swap_test.go b/swap/swap_test.go index a2d18a7164..552369e851 100644 --- a/swap/swap_test.go +++ b/swap/swap_test.go @@ -560,7 +560,7 @@ func TestDisconnectThreshold(t *testing.T) { amount := DefaultDisconnectThreshold.Value() // leave balance exactly at disconnect threshold - swap.Add((&amount).Int64(), testPeer.Peer) + swap.Add(amount.Int64(), testPeer.Peer) // account for traffic which increases debt err := swap.Add(1, testPeer.Peer) if err == nil { @@ -584,7 +584,7 @@ func TestPaymentThreshold(t *testing.T) { testPeer := newDummyPeerWithSpec(Spec) swap.addPeer(testPeer.Peer, swap.owner.address, swap.GetParams().ContractAddress) amount := DefaultPaymentThreshold.Value() - if err := swap.Add(-(&amount).Int64(), testPeer.Peer); err != nil { + if err := swap.Add(-amount.Int64(), testPeer.Peer); err != nil { t.Fatal() } @@ -646,7 +646,7 @@ func TestResetBalance(t *testing.T) { if err != nil { t.Fatal(err) } - creditorBalance, err := int256.NewInt256(*new(big.Int).Mul(big.NewInt(-1), &amount)) + creditorBalance, err := int256.NewInt256(new(big.Int).Mul(big.NewInt(-1), amount)) if err != nil { t.Fatal(err) } @@ -835,7 +835,7 @@ func calculateExpectedBalances(t *testing.T, swap *Swap, bookings []booking) map peerID := booking.peer.ID() peerBalance, ok := expectedBalances[peerID] if !ok { - peerBalance = new(int256.Int256) + peerBalance = int256.Int256From(0) } // peer balance should only be affected if debt is being reduced or if balance is smaller than disconnect threshold if peerBalance.Cmp(swap.params.DisconnectThreshold) < 0 || booking.amount.Cmp(int256.Int256From(0)) < 0 { @@ -1328,7 +1328,7 @@ func TestSwapLogToFile(t *testing.T) { ta := testAmount.Value() debitorAmount, err := int256.NewInt256(ta) - creditorAmount, err := int256.NewInt256(*new(big.Int).Mul(big.NewInt(-1), &ta)) + creditorAmount, err := int256.NewInt256(new(big.Int).Mul(big.NewInt(-1), ta)) // set balances arbitrarily if err = debitor.setBalance(debitorAmount); err != nil { t.Fatal(err) From 8be556e5391029b940c15aebc8e3eb4210420b50 Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 30 Mar 2020 17:09:29 -0300 Subject: [PATCH 69/70] remove unneeded change to go.mod --- go.mod | 1 - 1 file changed, 1 deletion(-) diff --git a/go.mod b/go.mod index 53a0a5d33c..a64125cf9a 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,6 @@ require ( github.com/googleapis/gnostic v0.0.0-20190624222214-25d8b0b66985 // indirect github.com/gorilla/mux v1.7.3 // indirect github.com/hashicorp/golang-lru v0.5.3 - github.com/influxdata/influxdb v0.0.0-20180221223340-01288bdb0883 github.com/json-iterator/go v1.1.7 // indirect github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/kylelemons/godebug v1.1.0 // indirect From 0f6e721e541d0bcb72a41fea71e1120e72fd1f2a Mon Sep 17 00:00:00 2001 From: mortelli Date: Mon, 30 Mar 2020 18:08:08 -0300 Subject: [PATCH 70/70] swap: small refactor to tests --- swap/protocol_test.go | 7 ++++--- swap/swap.go | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/swap/protocol_test.go b/swap/protocol_test.go index 1f079f68ce..b191e9a83c 100644 --- a/swap/protocol_test.go +++ b/swap/protocol_test.go @@ -306,7 +306,7 @@ func TestEmitCheque(t *testing.T) { } // check that the balance has been reset - if debitor.getBalance().Cmp(int256.Int256From(0)) != 0 { + if !debitor.getBalance().Equals(int256.Int256From(0)) { t.Fatalf("Expected debitor balance to have been reset to %d, but it is %v", 0, debitor.getBalance()) } recvCheque := debitor.getLastReceivedCheque() @@ -365,8 +365,8 @@ func TestTriggerPaymentThreshold(t *testing.T) { t.Fatal(err) } - paymentThreshold := DefaultPaymentThreshold.Value() - newBalance, err := int256.NewInt256(paymentThreshold) + // transform Uint256 to Int256 + newBalance, err := int256.NewInt256(DefaultPaymentThreshold.Value()) if err != nil { t.Fatal(err) } @@ -515,6 +515,7 @@ func TestTriggerDisconnectThreshold(t *testing.T) { // set the balance to manually be at DisconnectThreshold overDraft := 42 + // transform Uint256 to Int256 expectedBalance, err := int256.NewInt256((DefaultDisconnectThreshold).Value()) if err != nil { t.Fatal(err) diff --git a/swap/swap.go b/swap/swap.go index 27e610ae62..9550851240 100644 --- a/swap/swap.go +++ b/swap/swap.go @@ -324,6 +324,7 @@ func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error) { func (s *Swap) checkPaymentThresholdAndSendCheque(swapPeer *Peer) error { balance := swapPeer.getBalance() thresholdValue := s.params.PaymentThreshold.Value() + // transform Uint256 to Int256 threshold, err := int256.NewInt256(thresholdValue) if err != nil { return err