diff --git a/.github/actions/alicenet-cache/action.yml b/.github/actions/alicenet-cache/action.yml index ecac9ec3..9ec8f2ad 100644 --- a/.github/actions/alicenet-cache/action.yml +++ b/.github/actions/alicenet-cache/action.yml @@ -20,3 +20,4 @@ runs: - if: steps.alicenet-cache.outputs.cache-hit != 'true' shell: bash run: make generate-go + diff --git a/.github/actions/alicenet-config/action.yml b/.github/actions/alicenet-config/action.yml index 598c5074..047cb18c 100644 --- a/.github/actions/alicenet-config/action.yml +++ b/.github/actions/alicenet-config/action.yml @@ -13,3 +13,4 @@ runs: with: execution-folder: "./bridge" - uses: ./.github/actions/alicenet-cache + - uses: ./.github/actions/geth-eth-cache diff --git a/.github/actions/geth-eth-cache/action.yml b/.github/actions/geth-eth-cache/action.yml new file mode 100644 index 00000000..9e60a15d --- /dev/null +++ b/.github/actions/geth-eth-cache/action.yml @@ -0,0 +1,35 @@ +name: 'Setup geth, ethkey and its cache' +description: 'Setup geth, ethkey and its cache' +runs: + using: "composite" + steps: + - uses: actions/setup-go@v3 + with: + go-version: 1.18 + - uses: actions/cache@v3 + id: geth-eth-cache + with: + path: | + /usr/local/bin/geth + /usr/local/bin/ethkey + key: ${{ runner.os }}-geth-ethkey + - name: Check out ethereum repo for ethkey + if: steps.geth-eth-cache.outputs.cache-hit != 'true' + uses: actions/checkout@master + with: + repository: ethereum/go-ethereum + path: './go-ethereum' + - name: Install geth and ethkey + if: steps.geth-eth-cache.outputs.cache-hit != 'true' + shell: bash + run: | + REPO_PATH=$(pwd) + cd go-ethereum + sudo apt install make gcc + make all + cd /usr/local/bin + mv $REPO_PATH/go-ethereum/build/bin/ethkey /usr/local/bin + cd $REPO_PATH + sudo add-apt-repository -y ppa:ethereum/ethereum + sudo apt-get update + sudo apt-get install -y ethereum diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d6272bc..59ca7303 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,11 @@ name: Alicenet CI on: push: - branches: [main, candidate] + branches: [ main, candidate ] + paths: + - "blockchain" pull_request: - branches: [main, candidate] + branches: [ main, candidate ] env: NODE_VERSION: 16.x @@ -27,14 +29,12 @@ jobs: steps: - uses: actions/checkout@v3 - uses: ./.github/actions/node-cache - + solidity-unit-tests: runs-on: ubuntu-20.04 timeout-minutes: 15 strategy: matrix: - # when adding a new test folder to the smart contracts make sure to - # name it starting with 0-9 or A-Z include: - test-group: "[0-9a-dA-D]" - test-group: "[eE]" @@ -47,7 +47,6 @@ jobs: - test-group: "[f-qF-Q]" - test-group: "[r-sR-S]" - test-group: "[t-zT-Z]" - needs: solidity-build defaults: run: @@ -60,7 +59,7 @@ jobs: test-group: ${{ matrix.test-group }} sub-filter-include: ${{ matrix.sub-filter-include }} sub-filter-exclude: ${{ matrix.sub-filter-exclude }} - + solidity-linter: runs-on: ubuntu-20.04 timeout-minutes: 10 @@ -72,7 +71,7 @@ jobs: - uses: actions/checkout@v3 - uses: ./.github/actions/node-cache - run: npm run lint-solidity - + typescript-linter: runs-on: ubuntu-20.04 timeout-minutes: 10 @@ -86,14 +85,14 @@ jobs: - uses: ./.github/actions/node-cache - run: npm run clean && npm run compile && npm run typechain - run: npm run lint - + golang-build: runs-on: ${{ matrix.os }} timeout-minutes: 10 needs: solidity-build strategy: matrix: - os: [ubuntu-20.04] + os: [ ubuntu-20.04 ] steps: - name: "Sanitize branch name" run: | @@ -117,7 +116,7 @@ jobs: - uses: actions/checkout@v3 - uses: ./.github/actions/alicenet-config - run: go vet ./... - + golang-linter: runs-on: ubuntu-20.04 timeout-minutes: 10 @@ -131,23 +130,76 @@ jobs: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin - name: run golangci-lint run: golangci-lint run ./... - + golang-unit-tests: runs-on: ${{ matrix.os }} - timeout-minutes: 15 needs: golang-build strategy: matrix: - os: [ubuntu-20.04] + os: [ ubuntu-20.04 ] steps: + # Checkout and tool to format the test output - uses: actions/checkout@v3 - uses: ./.github/actions/alicenet-config - # tool to format the test output - name: Set up gotestfmt run: go install github.com/haveyoudebuggedit/gotestfmt/v2/cmd/gotestfmt@latest - # Run tests with nice formatting. Save the original log in /tmp/gotest.log - # packages where the tests are stuck: ["blockchain", "badgerTrie", "consensus", "transport"] - - name: Run tests + - name: Run unit tests + timeout-minutes: 20 run: | set -euo pipefail go test -json -v $(go list ./... | grep -Ev '/blockchain|/badgerTrie|/consensus/dman|/testutils') 2>&1 | tee /tmp/gotest.log | gotestfmt + + golang-blockchain-tests: + runs-on: ${{ matrix.os }} + needs: golang-build + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + os: [ ubuntu-20.04 ] + test-cmd: [ + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestShareDistribution_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestShareDistribution_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestShareDistribution_Group_3, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestRegisterTask_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestRegisterTask_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestRegisterTask_Group_3, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestMPKSubmission_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestMPKSubmission_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestKeyShareSubmission, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestGPKjSubmission_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestGPKjSubmission_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeShareDistributionTask_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeShareDistributionTask_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingShareDistributionTask_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingShareDistributionTask_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingRegistrationTask_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingRegistrationTask_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingKeySharesTask, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingGPKjTask_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestDisputeMissingGPKjTask_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestGPKjDispute, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestCompletion_Group_1, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestCompletion_Group_2, + github.com/MadBase/MadNet/blockchain/dkg/dkgtasks -run TestCompletion_Group_3, + github.com/MadBase/MadNet/blockchain, + github.com/MadBase/MadNet/blockchain/dkg, + github.com/MadBase/MadNet/blockchain/dkg/math, + github.com/MadBase/MadNet/blockchain/monitor, + github.com/MadBase/MadNet/blockchain/objects, + github.com/MadBase/MadNet/blockchain/tasks + ] + steps: + # Checkout and tool to format the test output + - uses: actions/checkout@v3 + - uses: ./.github/actions/alicenet-config + - name: Set up gotestfmt + run: go install github.com/haveyoudebuggedit/gotestfmt/v2/cmd/gotestfmt@latest + + # Run matrix blockchain unit tests + - name: Run tests ${{ matrix.test-cmd }} + timeout-minutes: 45 + run: | + set -euo pipefail + ./scripts/main.sh init 5 + go test -v -timeout=45m ${{ matrix.test-cmd }} diff --git a/blockchain/cancellation_test.go b/blockchain/cancellation_test.go index ce5fed5e..64918475 100644 --- a/blockchain/cancellation_test.go +++ b/blockchain/cancellation_test.go @@ -12,7 +12,7 @@ import ( const SLEEP_DURATION = 500 * time.Millisecond -func TestSleepWithContextComplete(t *testing.T) { +func TestCancellation_SleepWithContextComplete(t *testing.T) { ctx, _ := context.WithCancel(context.Background()) completed := false @@ -32,7 +32,7 @@ func TestSleepWithContextComplete(t *testing.T) { assert.True(t, completed) } -func TestSleepWithContextInterupted(t *testing.T) { +func TestCancellation_SleepWithContextInterrupted(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) completed := false @@ -48,10 +48,52 @@ func TestSleepWithContextInterupted(t *testing.T) { } wg.Done() }() - cancel() wg.Wait() assert.False(t, completed) } + +func TestCancellation_SlowReturn(t *testing.T) { + ctx, _ := context.WithCancel(context.Background()) + + type args struct { + ctx context.Context + delay time.Duration + value bool + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "Test slow Return success", + args: args{ + ctx: ctx, + delay: 5000 * time.Millisecond, + value: true, + }, + want: true, + }, + { + name: "Test slow Return quicker delay", + args: args{ + ctx: ctx, + delay: 500 * time.Millisecond, + value: false, + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + start := time.Now() + slowReturn, _ := blockchain.SlowReturn(tt.args.ctx, tt.args.delay, tt.args.value) + assert.Equalf(t, tt.want, slowReturn, "SlowReturn(%v, %v, %v)", tt.args.ctx, tt.args.delay, tt.args.value) + elapsed := time.Since(start) + assert.GreaterOrEqual(t, elapsed, tt.args.delay, "Delay time has not been respected") + }) + } +} diff --git a/blockchain/deposit_test.go b/blockchain/deposit_test.go deleted file mode 100644 index 5d0f8db5..00000000 --- a/blockchain/deposit_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package blockchain_test - -/* -import ( - "context" - "math/big" - "testing" - - "github.com/MadBase/MadNet/blockchain/interfaces" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -type DepositTestSuite struct { - suite.Suite - eth interfaces.Ethereum - callOpts *bind.CallOpts - txnOpts *bind.TransactOpts -} - -func (s *DepositTestSuite) SetupTest() { - t := s.T() - eth, err := setupEthereum(t, 4) - assert.Nil(t, err) - c := eth.Contracts() - - s.eth = eth - ctx := context.TODO() - - testAcct := eth.GetDefaultAccount() - - err = eth.UnlockAccount(testAcct) - if err != nil { - panic(err) - } - - bal, _ := eth.GetBalance(testAcct.Address) - t.Logf("ether balance of %v is %v", testAcct.Address.Hex(), bal) - - // Deployer starts with tokens, so has to transfer - txnOpts, _ := eth.GetTransactionOpts(ctx, testAcct) - _, err = c.UtilityToken().Transfer(txnOpts, testAcct.Address, InitialAllowance) - assert.Nil(t, err) - eth.Commit() - - assert.Nilf(t, err, "Initial transfer of %v to %v failed: %v", InitialAllowance, testAcct.Address.Hex(), err) - if err == nil { - t.Logf("Initial transfer of %v tokens to %v succeeded.", InitialAllowance, testAcct.Address.Hex()) - } - - s.callOpts = eth.GetCallOpts(ctx, eth.GetDefaultAccount()) - s.txnOpts, err = eth.GetTransactionOpts(ctx, eth.GetDefaultAccount()) - assert.Nil(t, err, "Failed to build txnOpts") -} - -func (s *DepositTestSuite) TestDepositEvent() { - t := s.T() - eth := s.eth - c := eth.Contracts() - - bal, _ := c.UtilityToken().BalanceOf(s.callOpts, eth.GetDefaultAccount().Address) - t.Logf("utility token balance of %v is %v", eth.GetDefaultAccount().Address.Hex(), bal) - - bal, _ = eth.GetBalance(eth.GetDefaultAccount().Address) - t.Logf("ether balance of %v is %v", eth.GetDefaultAccount().Address.Hex(), bal) - - // Approve deposit contract to withdrawh.GetDefaultAccount()) - txn, err := c.UtilityToken().Approve(s.txnOpts, c.DepositAddress(), big.NewInt(10000)) - assert.Nilf(t, err, "Approve failed by %v to %v", eth.GetDefaultAccount().Address.Hex(), c.DepositAddress().Hex()) - assert.NotNil(t, txn, "Approve failed: transaction is nil") - s.eth.Commit() - - // Tell deposit contract to withdraw - txn, err = c.Deposit().Deposit(s.txnOpts, big.NewInt(1000)) - assert.Nil(t, err, "Deposit failed") - assert.NotNilf(t, txn, "Deposit failed: transaction is nil") - s.eth.Commit() -} - -func TestDepositTestSuite(t *testing.T) { - suite.Run(t, new(DepositTestSuite)) -} -*/ diff --git a/blockchain/dkg/dkgtasks/completion_task_test.go b/blockchain/dkg/dkgtasks/completion_task_test.go index c4bcc375..ff327b9b 100644 --- a/blockchain/dkg/dkgtasks/completion_task_test.go +++ b/blockchain/dkg/dkgtasks/completion_task_test.go @@ -15,8 +15,12 @@ import ( ) // We complete everything correctly, happy path -func TestCompletionAllGood(t *testing.T) { +func TestCompletion_Group_1_AllGood(t *testing.T) { n := 4 + + err := dtest.InitializeValidatorFiles(5) + assert.Nil(t, err) + suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() ctx := context.Background() @@ -79,7 +83,7 @@ func TestCompletionAllGood(t *testing.T) { } } -func TestCompletion_StartFromCompletion(t *testing.T) { +func TestCompletion_Group_1_StartFromCompletion(t *testing.T) { n := 4 suite := StartFromCompletion(t, n, 100) defer suite.eth.Close() @@ -127,7 +131,7 @@ func TestCompletion_StartFromCompletion(t *testing.T) { // We begin by submitting invalid information. // This test is meant to raise an error resulting from an invalid argument // for the Ethereum interface. -func TestCompletionBad1(t *testing.T) { +func TestCompletion_Group_2_Bad1(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -151,7 +155,7 @@ func TestCompletionBad1(t *testing.T) { } // We test to ensure that everything behaves correctly. -func TestCompletionBad2(t *testing.T) { +func TestCompletion_Group_2_Bad2(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -176,7 +180,7 @@ func TestCompletionBad2(t *testing.T) { } // We complete everything correctly, but we do not complete in time -func TestCompletionBad3(t *testing.T) { +func TestCompletion_Group_2_Bad3(t *testing.T) { n := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() @@ -232,9 +236,9 @@ func TestCompletionBad3(t *testing.T) { } } -func TestCompletion_ShouldRetry_returnsFalse(t *testing.T) { +func TestCompletion_Group_3_ShouldRetry_returnsFalse(t *testing.T) { n := 4 - suite := StartFromCompletion(t, n, 100) + suite := StartFromCompletion(t, n, 40) defer suite.eth.Close() ctx := context.Background() eth := suite.eth @@ -270,7 +274,7 @@ func TestCompletion_ShouldRetry_returnsFalse(t *testing.T) { assert.False(t, tasks[0].ShouldRetry(ctx, logger, eth)) } -func TestCompletion_ShouldRetry_returnsTrue(t *testing.T) { +func TestCompletion_Group_3_ShouldRetry_returnsTrue(t *testing.T) { n := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/dispute_gpkj_task_test.go b/blockchain/dkg/dkgtasks/dispute_gpkj_task_test.go index 2785deeb..1c18ccf3 100644 --- a/blockchain/dkg/dkgtasks/dispute_gpkj_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_gpkj_task_test.go @@ -14,7 +14,7 @@ import ( ) // We test to ensure that everything behaves correctly. -func TestGPKjDisputeNoBadGPKj(t *testing.T) { +func TestGPKjDispute_NoBadGPKj(t *testing.T) { n := 5 unsubmittedGPKj := 0 suite := StartFromMPKSubmissionPhase(t, n, 100) @@ -84,7 +84,7 @@ func TestGPKjDisputeNoBadGPKj(t *testing.T) { } // Here, we have a malicious gpkj submission. -func TestGPKjDispute1Invalid(t *testing.T) { +func TestGPKjDispute_1Invalid(t *testing.T) { n := 5 unsubmittedGPKj := 0 suite := StartFromMPKSubmissionPhase(t, n, 100) @@ -168,7 +168,7 @@ func TestGPKjDispute1Invalid(t *testing.T) { // We test to ensure that everything behaves correctly. // Here, we have a malicious accusation. -func TestGPKjDisputeGoodMaliciousAccusation(t *testing.T) { +func TestGPKjDispute_GoodMaliciousAccusation(t *testing.T) { n := 5 unsubmittedGPKj := 0 suite := StartFromMPKSubmissionPhase(t, n, 100) diff --git a/blockchain/dkg/dkgtasks/dispute_missing_gpkj_task_test.go b/blockchain/dkg/dkgtasks/dispute_missing_gpkj_task_test.go index 2ace2240..07dd6bb8 100644 --- a/blockchain/dkg/dkgtasks/dispute_missing_gpkj_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_missing_gpkj_task_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestDisputeMissingGPKjTaskFourUnsubmittedGPKj_DoWork_Success(t *testing.T) { +func TestDisputeMissingGPKjTask_Group_1_FourUnsubmittedGPKj_DoWork_Success(t *testing.T) { n := 10 unsubmittedGPKj := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) @@ -67,7 +67,7 @@ func TestDisputeMissingGPKjTaskFourUnsubmittedGPKj_DoWork_Success(t *testing.T) assert.Equal(t, int64(unsubmittedGPKj), badParticipants.Int64()) } -func TestDisputeMissingGPKjTask_ShouldRetry_False(t *testing.T) { +func TestDisputeMissingGPKjTask_Group_1_ShouldRetry_False(t *testing.T) { n := 5 unsubmittedKeyShares := 1 suite := StartFromMPKSubmissionPhase(t, n, 300) @@ -122,7 +122,7 @@ func TestDisputeMissingGPKjTask_ShouldRetry_False(t *testing.T) { } } -func TestDisputeMissingGPKjTask_ShouldRetry_True(t *testing.T) { +func TestDisputeMissingGPKjTask_Group_1_ShouldRetry_True(t *testing.T) { n := 5 unsubmittedKeyShares := 1 suite := StartFromMPKSubmissionPhase(t, n, 100) @@ -172,7 +172,7 @@ func TestDisputeMissingGPKjTask_ShouldRetry_True(t *testing.T) { } } -func TestShouldAccuseOneValidatorWhoDidNotDistributeGPKjAndAnotherSubmittedBadGPKj(t *testing.T) { +func TestDisputeMissingGPKjTask_Group_2_ShouldAccuseOneValidatorWhoDidNotDistributeGPKjAndAnotherSubmittedBadGPKj(t *testing.T) { n := 5 suite := StartFromGPKjPhase(t, n, []int{4}, []int{3}, 100) defer suite.eth.Close() @@ -224,7 +224,7 @@ func TestShouldAccuseOneValidatorWhoDidNotDistributeGPKjAndAnotherSubmittedBadGP assert.False(t, isValidator) } -func TestShouldAccuseTwoValidatorWhoDidNotDistributeGPKjAndAnotherTwoSubmittedBadGPKj(t *testing.T) { +func TestDisputeMissingGPKjTask_Group_2_ShouldAccuseTwoValidatorWhoDidNotDistributeGPKjAndAnotherTwoSubmittedBadGPKj(t *testing.T) { n := 5 suite := StartFromGPKjPhase(t, n, []int{3, 4}, []int{1, 2}, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/dispute_missing_key_shares_task_test.go b/blockchain/dkg/dkgtasks/dispute_missing_key_shares_task_test.go index 8f6ce3f6..89c40f92 100644 --- a/blockchain/dkg/dkgtasks/dispute_missing_key_shares_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_missing_key_shares_task_test.go @@ -2,14 +2,13 @@ package dkgtasks_test import ( "context" - "testing" - "github.com/MadBase/MadNet/blockchain/objects" "github.com/MadBase/MadNet/logging" "github.com/stretchr/testify/assert" + "testing" ) -func TestDisputeMissingKeySharesTaskFourUnsubmittedKeyShare_DoWork_Success(t *testing.T) { +func TestDisputeMissingKeySharesTask_FourUnsubmittedKeyShare_DoWork_Success(t *testing.T) { n := 5 unsubmittedKeyShares := 4 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) @@ -57,7 +56,6 @@ func TestDisputeMissingKeySharesTaskFourUnsubmittedKeyShare_DoWork_Success(t *te for idx := 0; idx < n; idx++ { state := dkgStates[idx] disputeMissingKeyshareTask := suite.disputeMissingKeyshareTasks[idx] - dkgData := objects.NewETHDKGTaskData(state) err := disputeMissingKeyshareTask.Initialize(ctx, logger, eth, dkgData) assert.Nil(t, err) @@ -77,7 +75,7 @@ func TestDisputeMissingKeySharesTaskFourUnsubmittedKeyShare_DoWork_Success(t *te func TestDisputeMissingKeySharesTask_ShouldRetry_False(t *testing.T) { n := 5 unsubmittedKeyShares := 1 - suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 300) + suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 40) defer suite.eth.Close() ctx := context.Background() eth := suite.eth diff --git a/blockchain/dkg/dkgtasks/dispute_missing_registration_task_test.go b/blockchain/dkg/dkgtasks/dispute_missing_registration_task_test.go index 99eb60ca..109fa3c3 100644 --- a/blockchain/dkg/dkgtasks/dispute_missing_registration_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_missing_registration_task_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestDoTaskSuccessOneParticipantAccused(t *testing.T) { +func TestDisputeMissingRegistrationTask_Group_1_DoTaskSuccessOneParticipantAccused(t *testing.T) { n := 4 d := 1 suite := StartFromRegistrationOpenPhase(t, n, d, 100) @@ -40,7 +40,7 @@ func TestDoTaskSuccessOneParticipantAccused(t *testing.T) { assert.Equal(t, int64(d), badParticipants.Int64()) } -func TestDoTaskSuccessThreeParticipantAccused(t *testing.T) { +func TestDisputeMissingRegistrationTask_Group_1_DoTaskSuccessThreeParticipantAccused(t *testing.T) { n := 5 d := 3 suite := StartFromRegistrationOpenPhase(t, n, d, 100) @@ -71,7 +71,7 @@ func TestDoTaskSuccessThreeParticipantAccused(t *testing.T) { assert.Equal(t, int64(d), badParticipants.Int64()) } -func TestDoTaskSuccessAllParticipantsAreBad(t *testing.T) { +func TestDisputeMissingRegistrationTask_Group_1_DoTaskSuccessAllParticipantsAreBad(t *testing.T) { n := 5 d := 5 suite := StartFromRegistrationOpenPhase(t, n, d, 100) @@ -102,7 +102,7 @@ func TestDoTaskSuccessAllParticipantsAreBad(t *testing.T) { assert.Equal(t, int64(d), badParticipants.Int64()) } -func TestShouldRetryTrue(t *testing.T) { +func TestDisputeMissingRegistrationTask_Group_2_ShouldRetryTrue(t *testing.T) { suite := StartFromRegistrationOpenPhase(t, 5, 1, 100) defer suite.eth.Close() @@ -123,7 +123,7 @@ func TestShouldRetryTrue(t *testing.T) { } } -func TestShouldNotRetryAfterSuccessfullyAccusingAllMissingParticipants(t *testing.T) { +func TestDisputeMissingRegistrationTask_Group_2_ShouldNotRetryAfterSuccessfullyAccusingAllMissingParticipants(t *testing.T) { suite := StartFromRegistrationOpenPhase(t, 5, 0, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/dispute_missing_share_distribution_task_test.go b/blockchain/dkg/dkgtasks/dispute_missing_share_distribution_task_test.go index 60335138..61f17730 100644 --- a/blockchain/dkg/dkgtasks/dispute_missing_share_distribution_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_missing_share_distribution_task_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestShouldAccuseOneValidatorWhoDidNotDistributeShares(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_1_ShouldAccuseOneValidatorWhoDidNotDistributeShares(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{4}, []int{}, 100) defer suite.eth.Close() @@ -36,7 +36,7 @@ func TestShouldAccuseOneValidatorWhoDidNotDistributeShares(t *testing.T) { assert.Equal(t, uint64(1), badParticipants.Uint64()) } -func TestShouldAccuseAllValidatorsWhoDidNotDistributeShares(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_1_ShouldAccuseAllValidatorsWhoDidNotDistributeShares(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{0, 1, 2, 3, 4}, []int{}, 100) defer suite.eth.Close() @@ -62,7 +62,7 @@ func TestShouldAccuseAllValidatorsWhoDidNotDistributeShares(t *testing.T) { assert.Equal(t, uint64(n), badParticipants.Uint64()) } -func TestShouldNotAccuseValidatorsWhoDidDistributeShares(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_1_ShouldNotAccuseValidatorsWhoDidDistributeShares(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) defer suite.eth.Close() @@ -103,7 +103,7 @@ func TestShouldNotAccuseValidatorsWhoDidDistributeShares(t *testing.T) { assert.Equal(t, uint64(0), badParticipants.Uint64()) } -func TestDisputeMissingShareDistributionTask_ShouldRetryTrue(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_2_DisputeMissingShareDistributionTask_ShouldRetryTrue(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{0}, []int{}, 100) defer suite.eth.Close() @@ -122,7 +122,7 @@ func TestDisputeMissingShareDistributionTask_ShouldRetryTrue(t *testing.T) { } } -func TestDisputeMissingShareDistributionTask_ShouldRetryFalse(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_2_DisputeMissingShareDistributionTask_ShouldRetryFalse(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) defer suite.eth.Close() @@ -150,7 +150,7 @@ func TestDisputeMissingShareDistributionTask_ShouldRetryFalse(t *testing.T) { } } -func TestShouldAccuseOneValidatorWhoDidNotDistributeSharesAndAnotherSubmittedBadShares(t *testing.T) { +func TestDisputeMissingShareDistributionTask_Group_2_ShouldAccuseOneValidatorWhoDidNotDistributeSharesAndAnotherSubmittedBadShares(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{4}, []int{3}, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/dispute_share_distribution_task_test.go b/blockchain/dkg/dkgtasks/dispute_share_distribution_task_test.go index 96d1188b..75402e05 100644 --- a/blockchain/dkg/dkgtasks/dispute_share_distribution_task_test.go +++ b/blockchain/dkg/dkgtasks/dispute_share_distribution_task_test.go @@ -17,7 +17,7 @@ import ( ) // We test to ensure that everything behaves correctly. -func TestShareDisputeGoodAllValid(t *testing.T) { +func TestDisputeShareDistributionTask_Group_1_GoodAllValid(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) defer suite.eth.Close() @@ -65,7 +65,7 @@ func TestShareDisputeGoodAllValid(t *testing.T) { // In this test, we have one validator submit invalid information. // This causes another validator to submit a dispute against him, // causing a stake-slashing event. -func TestShareDisputeGoodMaliciousShare(t *testing.T) { +func TestDisputeShareDistributionTask_Group_1_GoodMaliciousShare(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -151,7 +151,7 @@ func TestShareDisputeGoodMaliciousShare(t *testing.T) { // We begin by submitting invalid information. // This test is meant to raise an error resulting from an invalid argument // for the Ethereum interface. -func TestShareDisputeBad1(t *testing.T) { +func TestDisputeShareDistributionTask_Group_1_Bad1(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -179,7 +179,7 @@ func TestShareDisputeBad1(t *testing.T) { // for the Ethereum interface; // this should raise an error resulting from not successfully completing // ShareDistribution phase. -func TestShareDisputeBad2(t *testing.T) { +func TestDisputeShareDistributionTask_Group_2_Bad2(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -208,7 +208,7 @@ func TestShareDisputeBad2(t *testing.T) { } } -func TestDisputeShareDistributionTask_DoRetry_returnsFalse(t *testing.T) { +func TestDisputeShareDistributionTask_Group_2_DoRetry_returnsFalse(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) defer suite.eth.Close() @@ -254,7 +254,7 @@ func TestDisputeShareDistributionTask_DoRetry_returnsFalse(t *testing.T) { } } -func TestDisputeShareDistributionTask_DoRetry_returnsTrue(t *testing.T) { +func TestDisputeShareDistributionTask_Group_2_DoRetry_returnsTrue(t *testing.T) { n := 5 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/dkgtasks_test.go b/blockchain/dkg/dkgtasks/dkgtasks_test.go index 36b4abc5..309992a7 100644 --- a/blockchain/dkg/dkgtasks/dkgtasks_test.go +++ b/blockchain/dkg/dkgtasks/dkgtasks_test.go @@ -142,6 +142,9 @@ func advanceTo(t *testing.T, eth interfaces.Ethereum, target uint64) { Params: make([]byte, 0), } + if target < currentBlock { + return + } blocksToMine := target - currentBlock var blocksToMineString = "0x" + strconv.FormatUint(blocksToMine, 16) diff --git a/blockchain/dkg/dkgtasks/gpkj_submission_task_test.go b/blockchain/dkg/dkgtasks/gpkj_submission_task_test.go index abb4f39f..37bde328 100644 --- a/blockchain/dkg/dkgtasks/gpkj_submission_task_test.go +++ b/blockchain/dkg/dkgtasks/gpkj_submission_task_test.go @@ -15,7 +15,7 @@ import ( ) //We test to ensure that everything behaves correctly. -func TestGPKjSubmissionGoodAllValid(t *testing.T) { +func TestGPKjSubmission_Group_1_GoodAllValid(t *testing.T) { n := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() @@ -57,7 +57,7 @@ func TestGPKjSubmissionGoodAllValid(t *testing.T) { // We begin by submitting invalid information. // Here, we submit nil for the state interface; // this should raise an error. -func TestGPKjSubmissionBad1(t *testing.T) { +func TestGPKjSubmission_Group_1_Bad1(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -84,7 +84,7 @@ func TestGPKjSubmissionBad1(t *testing.T) { // We test to ensure that everything behaves correctly. // Here, we should raise an error because we did not successfully complete // the key share submission phase. -func TestGPKjSubmissionBad2(t *testing.T) { +func TestGPKjSubmission_Group_1_Bad2(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -113,7 +113,7 @@ func TestGPKjSubmissionBad2(t *testing.T) { // One or more validators should submit invalid gpkj information; // that is, the gpkj public key and signature should not verify. // This should result in no submission. -func TestGPKjSubmissionBad3(t *testing.T) { +func TestGPKjSubmission_Group_2_Bad3(t *testing.T) { // Perform correct registration setup. // Perform correct share submission @@ -156,7 +156,7 @@ func TestGPKjSubmissionBad3(t *testing.T) { assert.NotNil(t, err) } -func TestGPKjSubmission_ShouldRetry_returnsFalse(t *testing.T) { +func TestGPKjSubmission_Group_2_ShouldRetry_returnsFalse(t *testing.T) { n := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() @@ -184,7 +184,7 @@ func TestGPKjSubmission_ShouldRetry_returnsFalse(t *testing.T) { } } -func TestGPKjSubmission_ShouldRetry_returnsTrue(t *testing.T) { +func TestGPKjSubmission_Group_2_ShouldRetry_returnsTrue(t *testing.T) { n := 4 suite := StartFromMPKSubmissionPhase(t, n, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/keyshare_submission_task_test.go b/blockchain/dkg/dkgtasks/keyshare_submission_task_test.go index c4bf0676..d920ec52 100644 --- a/blockchain/dkg/dkgtasks/keyshare_submission_task_test.go +++ b/blockchain/dkg/dkgtasks/keyshare_submission_task_test.go @@ -11,7 +11,7 @@ import ( ) // We test to ensure that everything behaves correctly. -func TestKeyShareSubmissionGoodAllValid(t *testing.T) { +func TestKeyShareSubmission_GoodAllValid(t *testing.T) { n := 5 suite := StartFromKeyShareSubmissionPhase(t, n, 0, 100) defer suite.eth.Close() @@ -42,7 +42,7 @@ func TestKeyShareSubmissionGoodAllValid(t *testing.T) { // We raise an error with invalid inputs. // This comes from invalid SecretValue in state. // In practice, this should never arise, though. -func TestKeyShareSubmissionBad3(t *testing.T) { +func TestKeyShareSubmission_Bad3(t *testing.T) { n := 5 var phaseLength uint16 = 100 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, phaseLength) @@ -68,7 +68,7 @@ func TestKeyShareSubmissionBad3(t *testing.T) { // We raise an error with invalid inputs. // Here, we mess up KeyShare information before submission // so that we raise an error on submission. -func TestKeyShareSubmissionBad4(t *testing.T) { +func TestKeyShareSubmission_Bad4(t *testing.T) { n := 5 var phaseLength uint16 = 100 suite := StartFromShareDistributionPhase(t, n, []int{}, []int{}, phaseLength) diff --git a/blockchain/dkg/dkgtasks/mpk_submission_task_test.go b/blockchain/dkg/dkgtasks/mpk_submission_task_test.go index fdbcf7e9..21becae2 100644 --- a/blockchain/dkg/dkgtasks/mpk_submission_task_test.go +++ b/blockchain/dkg/dkgtasks/mpk_submission_task_test.go @@ -15,7 +15,7 @@ import ( ) //We test to ensure that everything behaves correctly. -func TestMPKSubmissionGoodAllValid(t *testing.T) { +func TestMPKSubmission_Group_1_GoodAllValid(t *testing.T) { n := 4 suite := StartFromKeyShareSubmissionPhase(t, n, 0, 100) defer suite.eth.Close() @@ -71,7 +71,7 @@ func TestMPKSubmissionGoodAllValid(t *testing.T) { // In this test, *no* validator should submit an mpk. // After ending the MPK submission phase, validators should attempt // to submit the mpk; this should raise an error. -func TestMPKSubmissionBad1(t *testing.T) { +func TestMPKSubmission_Group_1_Bad1(t *testing.T) { // Perform correct registration setup. // Perform correct share submission @@ -108,7 +108,7 @@ func TestMPKSubmissionBad1(t *testing.T) { // We force an error. // This is caused by submitting invalid state information (state is nil). -func TestMPKSubmissionBad2(t *testing.T) { +func TestMPKSubmission_Group_1_Bad2(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -134,7 +134,7 @@ func TestMPKSubmissionBad2(t *testing.T) { // We force an error. // This is caused by submitting invalid state information by not successfully // completing KeyShareSubmission phase. -func TestMPKSubmissionBad4(t *testing.T) { +func TestMPKSubmission_Group_2_Bad4(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -156,9 +156,9 @@ func TestMPKSubmissionBad4(t *testing.T) { assert.NotNil(t, err) } -func TestMPKSubmission_ShouldRetry_returnsFalse(t *testing.T) { +func TestMPKSubmission_Group_2_ShouldRetry_returnsFalse(t *testing.T) { n := 4 - suite := StartFromKeyShareSubmissionPhase(t, n, 0, 100) + suite := StartFromKeyShareSubmissionPhase(t, n, 0, 40) defer suite.eth.Close() ctx := context.Background() eth := suite.eth @@ -195,7 +195,7 @@ func TestMPKSubmission_ShouldRetry_returnsFalse(t *testing.T) { assert.False(t, tasks[0].ShouldRetry(ctx, logger, eth)) } -func TestMPKSubmission_ShouldRetry_returnsTrue(t *testing.T) { +func TestMPKSubmission_Group_2_ShouldRetry_returnsTrue(t *testing.T) { n := 4 suite := StartFromKeyShareSubmissionPhase(t, n, 0, 100) defer suite.eth.Close() @@ -213,7 +213,7 @@ func TestMPKSubmission_ShouldRetry_returnsTrue(t *testing.T) { } } -func TestMPKSubmission_LeaderElection(t *testing.T) { +func TestMPKSubmission_Group_2_LeaderElection(t *testing.T) { n := 4 suite := StartFromKeyShareSubmissionPhase(t, n, 0, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dkgtasks/register_task_test.go b/blockchain/dkg/dkgtasks/register_task_test.go index c45069b5..0e5d3b54 100644 --- a/blockchain/dkg/dkgtasks/register_task_test.go +++ b/blockchain/dkg/dkgtasks/register_task_test.go @@ -18,7 +18,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestRegisterTask(t *testing.T) { +func TestRegisterTask_Group_1_Task(t *testing.T) { n := 5 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) tr := &objects.TypeRegistry{} @@ -103,7 +103,7 @@ func TestRegisterTask(t *testing.T) { // We attempt valid registration. Everything should succeed. // This test calls Initialize and DoWork. -func TestRegistrationGood2(t *testing.T) { +func TestRegisterTask_Group_1_Good2(t *testing.T) { n := 6 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) @@ -190,7 +190,7 @@ func TestRegistrationGood2(t *testing.T) { // We attempt to submit an invalid transport public key (a point not on the curve). // This should raise an error and not allow that participant to proceed. -func TestRegistrationBad1(t *testing.T) { +func TestRegisterTask_Group_1_Bad1(t *testing.T) { n := 5 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) @@ -250,7 +250,7 @@ func TestRegistrationBad1(t *testing.T) { // We attempt to submit an invalid transport public key (submit identity element). // This should raise an error and not allow that participant to proceed. -func TestRegistrationBad2(t *testing.T) { +func TestRegisterTask_Group_2_Bad2(t *testing.T) { n := 7 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) @@ -307,7 +307,7 @@ func TestRegistrationBad2(t *testing.T) { } // The initialization should fail because we dont allow less than 4 validators -func TestRegistrationBad4(t *testing.T) { +func TestRegisterTask_Group_2_Bad4(t *testing.T) { n := 3 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) @@ -338,7 +338,7 @@ func TestRegistrationBad4(t *testing.T) { // We attempt invalid registration. // Here, we try to register after registration has closed. // This should raise an error. -func TestRegistrationBad5(t *testing.T) { +func TestRegisterTask_Group_2_Bad5(t *testing.T) { n := 5 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) @@ -394,7 +394,7 @@ func TestRegistrationBad5(t *testing.T) { } // ShouldRetry() return false because the registration was successful -func TestRegisterTaskShouldRetryFalse(t *testing.T) { +func TestRegisterTask_Group_3_ShouldRetryFalse(t *testing.T) { n := 5 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) @@ -483,7 +483,7 @@ func TestRegisterTaskShouldRetryFalse(t *testing.T) { } // ShouldRetry() return true because the registration was unsuccessful -func TestRegisterTaskShouldRetryTrue(t *testing.T) { +func TestRegisterTask_Group_3_ShouldRetryTrue(t *testing.T) { n := 5 ecdsaPrivateKeys, accounts := dtest.InitializePrivateKeysAndAccounts(n) diff --git a/blockchain/dkg/dkgtasks/share_distribution_task_test.go b/blockchain/dkg/dkgtasks/share_distribution_task_test.go index 46edc4cd..8e9f898c 100644 --- a/blockchain/dkg/dkgtasks/share_distribution_task_test.go +++ b/blockchain/dkg/dkgtasks/share_distribution_task_test.go @@ -16,7 +16,7 @@ import ( ) //Here we test the happy path. -func TestShareDistributionGood(t *testing.T) { +func TestShareDistribution_Group_1_Good(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -44,7 +44,7 @@ func TestShareDistributionGood(t *testing.T) { // Here we test for invalid share distribution. // One validator attempts to submit invalid commitments (invalid elliptic curve point). // This should result in a failed submission. -func TestShareDistributionBad1(t *testing.T) { +func TestShareDistribution_Group_1_Bad1(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -82,8 +82,7 @@ func TestShareDistributionBad1(t *testing.T) { com[0][1].Add(com[0][1], big.NewInt(1)) } - err = task.DoWork(ctx, logger, suite.eth) - assert.Nil(t, err) + task.DoWork(ctx, logger, suite.eth) suite.eth.Commit() @@ -108,7 +107,7 @@ func TestShareDistributionBad1(t *testing.T) { // Here we test for invalid share distribution. // One validator attempts to submit invalid commitments (identity element). // This should result in a failed submission. -func TestShareDistributionBad2(t *testing.T) { +func TestShareDistribution_Group_1_Bad2(t *testing.T) { n := 4 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -146,8 +145,7 @@ func TestShareDistributionBad2(t *testing.T) { com[0][1].Set(common.Big0) } - err = task.DoWork(ctx, logger, suite.eth) - assert.Nil(t, err) + task.DoWork(ctx, logger, suite.eth) suite.eth.Commit() @@ -172,7 +170,7 @@ func TestShareDistributionBad2(t *testing.T) { // Here we test for invalid share distribution. // One validator attempts to submit invalid commitments (incorrect commitment length) // This should result in a failed submission. -func TestShareDistributionBad4(t *testing.T) { +func TestShareDistribution_Group_2_Bad4(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -212,8 +210,7 @@ func TestShareDistributionBad4(t *testing.T) { state.Participants[accounts[idx].Address].Commitments = com } - err = task.DoWork(ctx, logger, eth) - assert.Nil(t, err) + task.DoWork(ctx, logger, eth) eth.Commit() @@ -238,7 +235,7 @@ func TestShareDistributionBad4(t *testing.T) { // Here we test for invalid share distribution. // One validator attempts to submit invalid commitments (incorrect encrypted shares length) // This should result in a failed submission. -func TestShareDistributionBad5(t *testing.T) { +func TestShareDistribution_Group_2_Bad5(t *testing.T) { n := 6 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -265,8 +262,7 @@ func TestShareDistributionBad5(t *testing.T) { state.Participants[accounts[idx].Address].EncryptedShares = encryptedShares } - err = task.DoWork(ctx, logger, eth) - assert.Nil(t, err) + task.DoWork(ctx, logger, eth) eth.Commit() @@ -290,7 +286,7 @@ func TestShareDistributionBad5(t *testing.T) { // We begin by submitting invalid information; // we submit nil state information -func TestShareDistributionBad6(t *testing.T) { +func TestShareDistribution_Group_2_Bad6(t *testing.T) { n := 5 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -315,7 +311,7 @@ func TestShareDistributionBad6(t *testing.T) { // We test to ensure that everything behaves correctly. // We submit invalid state information (again). -func TestShareDistributionBad7(t *testing.T) { +func TestShareDistribution_Group_3_Bad7(t *testing.T) { n := 4 ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(n) logger := logging.GetLogger("ethereum") @@ -339,7 +335,7 @@ func TestShareDistributionBad7(t *testing.T) { } } -func TestShareDistributionShouldRetryTrue(t *testing.T) { +func TestShareDistribution_Group_3_ShouldRetryTrue(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() @@ -362,7 +358,7 @@ func TestShareDistributionShouldRetryTrue(t *testing.T) { } } -func TestShareDistributionShouldRetryFalse(t *testing.T) { +func TestShareDistribution_Group_3_ShouldRetryFalse(t *testing.T) { n := 5 suite := StartFromRegistrationOpenPhase(t, n, 0, 100) defer suite.eth.Close() diff --git a/blockchain/dkg/dtest/setup.go b/blockchain/dkg/dtest/setup.go index 3fb84043..31ee6e9b 100644 --- a/blockchain/dkg/dtest/setup.go +++ b/blockchain/dkg/dtest/setup.go @@ -16,7 +16,7 @@ import ( "os" "os/exec" "path/filepath" - "runtime" + "strconv" "strings" "syscall" "testing" @@ -284,20 +284,23 @@ func GenerateGPKJ(dkgStates []*objects.DkgState) { } func GetMadnetRootPath() []string { - _, b, _, _ := runtime.Caller(0) - // Root folder of this project - root := filepath.Dir(b) - pathNodes := strings.Split(root, string(os.PathSeparator)) rootPath := []string{string(os.PathSeparator)} - //rootPath[0] = string(os.PathSeparator) - for _, node := range pathNodes { - rootPath = append(rootPath, node) + cmd := exec.Command("go", "list", "-m", "-f", "'{{.Dir}}'", "github.com/MadBase/MadNet") + stdout, err := cmd.Output() + if err != nil { + log.Printf("Error getting project root path: %v", err) + return rootPath + } - if node == "MadNet" { - break - } + path := string(stdout) + path = strings.ReplaceAll(path, "'", "") + path = strings.ReplaceAll(path, "\n", "") + + pathNodes := strings.Split(path, string(os.PathSeparator)) + for _, pathNode := range pathNodes { + rootPath = append(rootPath, pathNode) } return rootPath @@ -496,12 +499,20 @@ func StartHardHatNode(eth *blockchain.EthereumDetails) error { eth.SetClose(func() error { fmt.Printf("closing hardhat node %v..\n", cmd.Process.Pid) err := cmd.Process.Signal(syscall.SIGTERM) - - // err := cmd.Process.Kill() if err != nil { return err } + //err = syscall.Kill(syscall.Getpid(), syscall.SIGINT) + //if err != nil { + // return err + //} + + //err = cmd.Process.Kill() + //if err != nil { + // return err + //} + _, err = cmd.Process.Wait() if err != nil { return err @@ -514,6 +525,30 @@ func StartHardHatNode(eth *blockchain.EthereumDetails) error { return nil } +func InitializeValidatorFiles(n int) error { + + rootPath := GetMadnetRootPath() + scriptPath := append(rootPath, "scripts") + scriptPath = append(scriptPath, "main.sh") + scriptPathJoined := filepath.Join(scriptPath...) + fmt.Println("scriptPathJoined2: ", scriptPathJoined) + + cmd := exec.Cmd{ + Path: scriptPathJoined, + Args: []string{scriptPathJoined, "init", strconv.Itoa(n)}, + Dir: filepath.Join(rootPath...), + Stdout: os.Stdout, + Stderr: os.Stderr, + } + + err := cmd.Start() + if err != nil { + return fmt.Errorf("could not generate validator files: %s", err) + } + + return nil +} + func StartDeployScripts(eth *blockchain.EthereumDetails, ctx context.Context) error { rootPath := GetMadnetRootPath() @@ -540,7 +575,8 @@ func StartDeployScripts(eth *blockchain.EthereumDetails, ctx context.Context) er // if there is an error with our execution // handle it here if err != nil { - return fmt.Errorf("could not execute deploy script: %s", err) + log.Printf("Could not execute deploy script: %s", err) + return err } // inits contracts diff --git a/blockchain/dkg/math/dkg_test.go b/blockchain/dkg/math/dkg_test.go index 9a35a123..dad26d9e 100644 --- a/blockchain/dkg/math/dkg_test.go +++ b/blockchain/dkg/math/dkg_test.go @@ -15,8 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) - -func TestCalculateThreshold(t *testing.T) { +func TestMath_CalculateThreshold(t *testing.T) { threshold := math.ThresholdForUserCount(4) assert.Equal(t, 2, threshold) threshold = math.ThresholdForUserCount(5) @@ -31,7 +30,7 @@ func TestCalculateThreshold(t *testing.T) { assert.Equal(t, 6, threshold) } -func TestInverseArrayForUserCount(t *testing.T) { +func TestMath_InverseArrayForUserCount(t *testing.T) { n := 3 _, err := math.InverseArrayForUserCount(n) if err == nil { @@ -59,7 +58,7 @@ func TestInverseArrayForUserCount(t *testing.T) { } } -func TestGenerateKeys(t *testing.T) { +func TestMath_GenerateKeys(t *testing.T) { private, public, err := math.GenerateKeys() assert.Nil(t, err, "error generating keys") @@ -70,7 +69,7 @@ func TestGenerateKeys(t *testing.T) { assert.NotNil(t, public[1], "public key missing element") } -func TestGenerateShares(t *testing.T) { +func TestMath_GenerateShares(t *testing.T) { // Number participants in key generation n := 4 threshold := math.ThresholdForUserCount(n) @@ -104,7 +103,7 @@ func TestGenerateShares(t *testing.T) { t.Logf("encryptedShares:%x privateCoefficients:%x commitments:%x", encryptedShares, privateCoefficients, commitments) } -func TestGenerateSharesBad(t *testing.T) { +func TestMath_GenerateSharesBad(t *testing.T) { _, _, _, err := math.GenerateShares(nil, objects.ParticipantList{}) if err == nil { t.Fatal("Should have raised error (0)") @@ -123,7 +122,7 @@ func TestGenerateSharesBad(t *testing.T) { } } -func TestVerifyDistributedSharesGood1(t *testing.T) { +func TestMath_VerifyDistributedSharesGood1(t *testing.T) { // Number participants in key generation n := 4 // Test with deterministic private coefficients @@ -148,7 +147,7 @@ func TestVerifyDistributedSharesGood1(t *testing.T) { } } -func TestVerifyDistributedSharesGood2(t *testing.T) { +func TestMath_VerifyDistributedSharesGood2(t *testing.T) { // Number participants in key generation n := 5 // Test with random private coefficients @@ -173,7 +172,7 @@ func TestVerifyDistributedSharesGood2(t *testing.T) { } } -func TestVerifyDistributedSharesGood3(t *testing.T) { +func TestMath_VerifyDistributedSharesGood3(t *testing.T) { // Number participants in key generation n := 7 // Test with deterministic private coefficients @@ -212,7 +211,7 @@ func TestVerifyDistributedSharesGood3(t *testing.T) { } } -func TestVerifyDistributedSharesGood4(t *testing.T) { +func TestMath_VerifyDistributedSharesGood4(t *testing.T) { // Number participants in key generation n := 4 // Test with deterministic private coefficients @@ -252,7 +251,7 @@ func TestVerifyDistributedSharesGood4(t *testing.T) { } } -func TestVerifyDistributedSharesBad1(t *testing.T) { +func TestMath_VerifyDistributedSharesBad1(t *testing.T) { // Test for raised error for nil arguments _, _, err := math.VerifyDistributedShares(nil, nil) if err == nil { @@ -265,7 +264,7 @@ func TestVerifyDistributedSharesBad1(t *testing.T) { } } -func TestVerifyDistributedSharesBad2(t *testing.T) { +func TestMath_VerifyDistributedSharesBad2(t *testing.T) { // Test for error upon invalid number of participants dkgState := &objects.DkgState{} dkgState.Index = 1 @@ -277,7 +276,7 @@ func TestVerifyDistributedSharesBad2(t *testing.T) { } } -func TestVerifyDistributedSharesBad3(t *testing.T) { +func TestMath_VerifyDistributedSharesBad3(t *testing.T) { // Test for error with invalid commitments and encrypted shares n := 4 threshold := math.ThresholdForUserCount(n) @@ -366,7 +365,7 @@ func TestVerifyDistributedSharesBad3(t *testing.T) { assert.NotNil(t, err) } -func TestGenerateKeyShare(t *testing.T) { +func TestMath_GenerateKeyShare(t *testing.T) { // Number participants in key generation n := 4 @@ -411,14 +410,14 @@ func TestGenerateKeyShare(t *testing.T) { t.Logf("keyShare1:%x keyShare1Proof:%x keyShare2:%x", keyShare1, keyShare1Proof, keyShare2) } -func TestGenerateKeyShareBad(t *testing.T) { +func TestMath_GenerateKeyShareBad(t *testing.T) { _, _, _, err := math.GenerateKeyShare(nil) if err == nil { t.Fatal("Should have raised error") } } -func TestGenerateMasterPublicKey(t *testing.T) { +func TestMath_GenerateMasterPublicKey(t *testing.T) { // Number participants in key generation n := 4 @@ -469,7 +468,7 @@ func TestGenerateMasterPublicKey(t *testing.T) { assert.NotNil(t, masterPublicKey[3], "missing element of master public key") } -func TestGenerateMasterPublicKeyBad(t *testing.T) { +func TestMath_GenerateMasterPublicKeyBad(t *testing.T) { keyShare1s := [][2]*big.Int{[2]*big.Int{nil, nil}} keyShare2s := [][4]*big.Int{} _, err := math.GenerateMasterPublicKey(keyShare1s, keyShare2s) @@ -491,7 +490,7 @@ func TestGenerateMasterPublicKeyBad(t *testing.T) { } } -func TestGenerateGroupKeys(t *testing.T) { +func TestMath_GenerateGroupKeys(t *testing.T) { // Number participants in key generation n := 4 @@ -547,7 +546,7 @@ func TestGenerateGroupKeys(t *testing.T) { //t.Logf("groupPrivate:%x groupPublic:%x groupSignature:%x", groupPrivate, groupPublic, groupSignature) } -func TestGenerateGroupKeysBad1(t *testing.T) { +func TestMath_GenerateGroupKeysBad1(t *testing.T) { // Initial Setup n := 4 deterministicShares := true @@ -585,7 +584,7 @@ func TestGenerateGroupKeysBad1(t *testing.T) { } } -func TestGenerateGroupKeysBad2(t *testing.T) { +func TestMath_GenerateGroupKeysBad2(t *testing.T) { // Initial Setup n := 4 deterministicShares := true @@ -614,7 +613,7 @@ func TestGenerateGroupKeysBad2(t *testing.T) { } } -func TestCategorizeGroupSigners(t *testing.T) { +func TestMath_CategorizeGroupSigners(t *testing.T) { n := 10 _, publishedPublicKeys, participants, commitmentArray := setupGroupSigners(t, n) @@ -625,7 +624,7 @@ func TestCategorizeGroupSigners(t *testing.T) { assert.Equal(t, 0, len(missing), "no participants should be missing") } -func TestCategorizeGroupSigners1Negative(t *testing.T) { +func TestMath_CategorizeGroupSigners1Negative(t *testing.T) { n := 30 logger := logging.GetLogger("dkg") @@ -642,7 +641,7 @@ func TestCategorizeGroupSigners1Negative(t *testing.T) { assert.Equal(t, 0, len(missing), "0 participants are missing") } -func TestCategorizeGroupSigners2Negative(t *testing.T) { +func TestMath_CategorizeGroupSigners2Negative(t *testing.T) { n := 10 threshold := math.ThresholdForUserCount(n) @@ -666,7 +665,7 @@ func TestCategorizeGroupSigners2Negative(t *testing.T) { assert.Equal(t, 0, len(missing)) } -func TestCategorizeGroupSignersBad(t *testing.T) { +func TestMath_CategorizeGroupSignersBad(t *testing.T) { n := 4 _, publishedPublicKeys, participants, commitmentArray := setupGroupSigners(t, n) threshold := math.ThresholdForUserCount(n) @@ -719,7 +718,7 @@ func TestCategorizeGroupSignersBad(t *testing.T) { } } -func TestCategorizeGroupSignersBad2(t *testing.T) { +func TestMath_CategorizeGroupSignersBad2(t *testing.T) { n := 4 _, publishedPublicKeys, participants, commitmentArray := setupGroupSigners(t, n) publishedPublicKeysBad := [][4]*big.Int{} diff --git a/blockchain/dkg/utilities_test.go b/blockchain/dkg/utilities_test.go index c941dacd..34a6dfa1 100644 --- a/blockchain/dkg/utilities_test.go +++ b/blockchain/dkg/utilities_test.go @@ -8,7 +8,7 @@ import ( "github.com/holiman/uint256" ) -func TestFoo(t *testing.T) { +func TestUtilities_AddOverflow(t *testing.T) { a := uint256.NewInt(4) b := uint256.NewInt(6).SetAllOne() c := uint256.NewInt(8) @@ -23,7 +23,7 @@ func TestFoo(t *testing.T) { t.Logf("ptr c:%p d:%p", c, d) } -func TestIntsToBigInts(t *testing.T) { +func TestUtilities_IntsToBigInts(t *testing.T) { ints := []int{1, 2, 3, 5, 8, 13} big1 := big.NewInt(1) big2 := big.NewInt(2) diff --git a/blockchain/ethdkg_test.go b/blockchain/ethdkg_test.go deleted file mode 100644 index d82e4ba4..00000000 --- a/blockchain/ethdkg_test.go +++ /dev/null @@ -1,10 +0,0 @@ -package blockchain_test - -import ( - "testing" -) - -func TestAccuse(t *testing.T) { - // eth, commit, err := setupEthereum() - -} diff --git a/blockchain/ethereum.go b/blockchain/ethereum.go index 0d96a5a3..87668e1e 100644 --- a/blockchain/ethereum.go +++ b/blockchain/ethereum.go @@ -308,7 +308,7 @@ func NewEthereumEndpoint( defer cancel() rpcClient, rpcErr := rpc.DialContext(ctx, endpoint) if rpcErr != nil { - logger.Errorf("Error in NewEthereumEndpoint at rpc.DialContext: %v", err) + logger.Errorf("Error in NewEthereumEndpoint at rpc.DialContext: %v", rpcErr) return nil, rpcErr } ethClient := ethclient.NewClient(rpcClient) diff --git a/blockchain/ethereum_test.go b/blockchain/ethereum_test.go index 6a3b33c3..08275905 100644 --- a/blockchain/ethereum_test.go +++ b/blockchain/ethereum_test.go @@ -2,8 +2,12 @@ package blockchain_test import ( "context" + "errors" + "fmt" + "io/fs" "math" "math/big" + "net" "testing" "time" @@ -28,7 +32,7 @@ func setupEthereum(t *testing.T, n int) interfaces.Ethereum { return eth } -func TestAccountsFound(t *testing.T) { +func TestEthereum_AccountsFound(t *testing.T) { eth := setupEthereum(t, 4) defer eth.Close() @@ -45,7 +49,7 @@ func TestAccountsFound(t *testing.T) { } -func TestHardhatNode(t *testing.T) { +func TestEthereum_HardhatNode(t *testing.T) { privateKeys, _ := dtest.InitializePrivateKeysAndAccounts(4) eth, err := blockchain.NewEthereumSimulator( @@ -92,3 +96,112 @@ func TestHardhatNode(t *testing.T) { t.Logf("done testing") } + +func TestEthereum_NewEthereumEndpoint(t *testing.T) { + + eth := setupEthereum(t, 4) + defer eth.Close() + + type args struct { + endpoint string + pathKeystore string + pathPasscodes string + defaultAccount string + timeout time.Duration + retryCount int + retryDelay time.Duration + finalityDelay int + txFeePercentageToIncrease int + txMaxFeeThresholdInGwei uint64 + txCheckFrequency time.Duration + txTimeoutForReplacement time.Duration + } + tests := []struct { + name string + args args + want bool + wantErr assert.ErrorAssertionFunc + }{ + + { + name: "Create new ethereum endpoint failing with passcode file not found", + args: args{"", "", "", "", 0, 0, 0, 0, 0, 0, 0, 0}, + want: false, + wantErr: func(t assert.TestingT, err error, i ...interface{}) bool { + _, ok := err.(*fs.PathError) + if !ok { + t.Errorf("Failing test with an unexpected error") + } + return ok + }, + }, + { + name: "Create new ethereum endpoint failing with specified account not found", + args: args{"", "", "../assets/test/passcodes.txt", "", 0, 0, 0, 0, 0, 0, 0, 0}, + want: false, + wantErr: func(t assert.TestingT, err error, i ...interface{}) bool { + if !errors.Is(err, blockchain.ErrAccountNotFound) { + t.Errorf("Failing test with an unexpected error") + } + return true + }, + }, + { + name: "Create new ethereum endpoint failing on Dial Context", + args: args{ + eth.GetEndpoint(), + "../assets/test/keys", + "../assets/test/passcodes.txt", + eth.GetDefaultAccount().Address.String(), + eth.Timeout(), + eth.RetryCount(), + eth.RetryDelay(), + int(eth.GetFinalityDelay()), + eth.GetTxFeePercentageToIncrease(), + eth.GetTxMaxFeeThresholdInGwei(), + eth.GetTxCheckFrequency(), + eth.GetTxTimeoutForReplacement(), + }, + want: false, + wantErr: func(t assert.TestingT, err error, i ...interface{}) bool { + _, ok := err.(*net.OpError) + if !ok { + t.Errorf("Failing test with an unexpected error") + } + return ok + }, + }, + { + name: "Create new ethereum endpoint returning EthereumDetails", + args: args{ + "http://localhost:8545", + "../assets/test/keys", + "../assets/test/passcodes.txt", + eth.GetDefaultAccount().Address.String(), + eth.Timeout(), + eth.RetryCount(), + eth.RetryDelay(), + int(eth.GetFinalityDelay()), + eth.GetTxFeePercentageToIncrease(), + eth.GetTxMaxFeeThresholdInGwei(), + eth.GetTxCheckFrequency(), + eth.GetTxTimeoutForReplacement(), + }, + want: true, + wantErr: func(t assert.TestingT, err error, i ...interface{}) bool { + return true + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := blockchain.NewEthereumEndpoint(tt.args.endpoint, tt.args.pathKeystore, tt.args.pathPasscodes, tt.args.defaultAccount, tt.args.timeout, tt.args.retryCount, tt.args.retryDelay, tt.args.finalityDelay, tt.args.txFeePercentageToIncrease, tt.args.txMaxFeeThresholdInGwei, tt.args.txCheckFrequency, tt.args.txTimeoutForReplacement) + if !tt.wantErr(t, err, fmt.Sprintf("NewEthereumEndpoint(%v, %v, %v, %v, %v, %v, %v, %v, %v, %v, %v, %v)", tt.args.endpoint, tt.args.pathKeystore, tt.args.pathPasscodes, tt.args.defaultAccount, tt.args.timeout, tt.args.retryCount, tt.args.retryDelay, tt.args.finalityDelay, tt.args.txFeePercentageToIncrease, tt.args.txMaxFeeThresholdInGwei, tt.args.txCheckFrequency, tt.args.txTimeoutForReplacement)) { + return + } + if tt.want { + assert.NotNilf(t, got, "Ethereum Details must not be nil") + } + }) + } +} diff --git a/blockchain/monitor/database_test.go b/blockchain/monitor/database_test.go deleted file mode 100644 index 8830741c..00000000 --- a/blockchain/monitor/database_test.go +++ /dev/null @@ -1,7 +0,0 @@ -package monitor_test - -import "testing" - -func TestDBFind(t *testing.T) { - -} diff --git a/blockchain/monitor/monitor_test.go b/blockchain/monitor/monitor_test.go index 8773bc2d..8a8a26b2 100644 --- a/blockchain/monitor/monitor_test.go +++ b/blockchain/monitor/monitor_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "github.com/MadBase/MadNet/blockchain/dkg/dtest" "math/big" "sync" "testing" @@ -167,7 +168,10 @@ func TestBidirectionalMarshaling(t *testing.T) { // setup adminHandler := mocks.NewMockAdminHandler() depositHandler := &mockDepositHandler{} - eth := mocks.NewMockBaseEthereum() + + ecdsaPrivateKeys, _ := dtest.InitializePrivateKeysAndAccounts(5) + eth := dtest.ConnectSimulatorEndpoint(t, ecdsaPrivateKeys, 333*time.Millisecond) + defer eth.Close() logger := logging.GetLogger("test") addr0 := common.HexToAddress("0x546F99F244b7B58B855330AE0E2BC1b30b41302F") @@ -179,8 +183,10 @@ func TestBidirectionalMarshaling(t *testing.T) { assert.Nil(t, err) populateMonitor(mon.State, addr0, EPOCH) + acct := eth.GetKnownAccounts()[0] + state := objects.NewDkgState(acct) mockTsk := &mockTask{ - DkgTask: dkgtasks.NewExecutionData(nil, 1, 40), + DkgTask: dkgtasks.NewExecutionData(state, 1, 40), } // Schedule some tasks mon.State.Schedule.Schedule(1, 2, mockTsk) diff --git a/blockchain/monitor/services_intg_test.go b/blockchain/monitor/services_intg_test.go index 6c287fa4..5ca1bb68 100644 --- a/blockchain/monitor/services_intg_test.go +++ b/blockchain/monitor/services_intg_test.go @@ -1,49 +1,58 @@ package monitor_test -/* -type ServicesSuite struct { - suite.Suite - eth interfaces.Ethereum -} - -func (s *ServicesSuite) SetupTest() { - t := s.T() - +import ( + "context" + "github.com/MadBase/MadNet/blockchain" + "github.com/MadBase/MadNet/blockchain/dkg/dtest" + "github.com/stretchr/testify/assert" + "math" + "math/big" + "testing" + "time" +) + +func TestRegistrationOpenEvent(t *testing.T) { + + privateKeys, _ := dtest.InitializePrivateKeysAndAccounts(4) eth, err := blockchain.NewEthereumSimulator( - "../../assets/test/keys", - "../../assets/test/passcodes.txt", - 3, - 2*time.Second, - 5*time.Second, + privateKeys, + 6, + 10*time.Second, + 30*time.Second, 0, - big.NewInt(9223372036854775807), - "0x26D3D8Ab74D62C26f1ACc220dA1646411c9880Ac", - "0x546F99F244b7B58B855330AE0E2BC1b30b41302F") + big.NewInt(math.MaxInt64), + 50, + math.MaxInt64, + 5*time.Second, + 30*time.Second) + defer eth.Close() assert.Nil(t, err, "Error creating Ethereum simulator") - - s.eth = eth -} - -func (s *ServicesSuite) TestRegistrationOpenEvent() { - t := s.T() - eth := s.eth c := eth.Contracts() assert.NotNil(t, c, "Need a *Contracts") - height, err := s.eth.GetCurrentHeight(context.TODO()) + err = dtest.StartHardHatNode(eth) + if err != nil { + t.Fatalf("error starting hardhat node: %v", err) + } + + t.Logf("waiting on hardhat node to start...") + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + err = dtest.WaitForHardHatNode(ctx) + if err != nil { + t.Fatalf("error: %v", err) + } + + height, err := eth.GetCurrentHeight(context.TODO()) assert.Nil(t, err, "could not get height") assert.Equal(t, uint64(0), height, "Height should be 0") - s.eth.Commit() + eth.Commit() - height, err = s.eth.GetCurrentHeight(context.TODO()) + height, err = eth.GetCurrentHeight(context.TODO()) assert.Nil(t, err, "could not get height") assert.Equal(t, uint64(1), height, "Height should be 1") } - -func TestServicesSuite(t *testing.T) { - suite.Run(t, new(ServicesSuite)) -} - -*/ diff --git a/blockchain/objects/dkg_state_test.go b/blockchain/objects/dkg_state_test.go index 1ba4b2e0..1b7d1848 100644 --- a/blockchain/objects/dkg_state_test.go +++ b/blockchain/objects/dkg_state_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestParticipantCopy(t *testing.T) { +func TestDKGState_ParticipantCopy(t *testing.T) { p := &objects.Participant{} addrBytes := make([]byte, 20) addrBytes[0] = 255 @@ -46,7 +46,7 @@ func TestParticipantCopy(t *testing.T) { } } -func TestParticipantListExtractIndices(t *testing.T) { +func TestDKGState_ParticipantListExtractIndices(t *testing.T) { p1 := &objects.Participant{Index: 1} p2 := &objects.Participant{Index: 2} p3 := &objects.Participant{Index: 3} @@ -65,7 +65,7 @@ func TestParticipantListExtractIndices(t *testing.T) { } } -func TestMarshalAndUnmarshalBigInt(t *testing.T) { +func TestDKGState_MarshalAndUnmarshalBigInt(t *testing.T) { // generate transport keys priv, pub, err := math.GenerateKeys() @@ -89,7 +89,7 @@ func TestMarshalAndUnmarshalBigInt(t *testing.T) { assert.Equal(t, pub, pub2) } -func TestMarshalAndUnmarshalAccount(t *testing.T) { +func TestDKGState_MarshalAndUnmarshalAccount(t *testing.T) { addr := common.Address{} addr.SetBytes([]byte("546F99F244b7B58B855330AE0E2BC1b30b41302F")) @@ -114,7 +114,7 @@ func TestMarshalAndUnmarshalAccount(t *testing.T) { assert.Equal(t, acct, *acct2) } -func TestMarshalAndUnmarshalParticipant(t *testing.T) { +func TestDKGState_MarshalAndUnmarshalParticipant(t *testing.T) { addr := common.Address{} addr.SetBytes([]byte("546F99F244b7B58B855330AE0E2BC1b30b41302F")) @@ -145,7 +145,7 @@ func TestMarshalAndUnmarshalParticipant(t *testing.T) { } -func TestMarshalAndUnmarshalDkgState(t *testing.T) { +func TestDKGState_MarshalAndUnmarshalDkgState(t *testing.T) { addr := common.Address{} addr.SetBytes([]byte("546F99F244b7B58B855330AE0E2BC1b30b41302F")) diff --git a/blockchain/objects/scheduler_test.go b/blockchain/objects/scheduler_test.go index 70d207d7..9f623665 100644 --- a/blockchain/objects/scheduler_test.go +++ b/blockchain/objects/scheduler_test.go @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestSchedule(t *testing.T) { +func TestScheduler_Schedule(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -33,7 +33,7 @@ func TestSchedule(t *testing.T) { assert.Equal(t, 4, s.Length()) } -func TestPurge(t *testing.T) { +func TestScheduler_Purge(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -55,7 +55,7 @@ func TestPurge(t *testing.T) { assert.Equal(t, 0, s.Length()) } -func TestPurgePrior(t *testing.T) { +func TestScheduler_PurgePrior(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -77,23 +77,7 @@ func TestPurgePrior(t *testing.T) { assert.Equal(t, 1, s.Length()) } -func TestFailSchedule(t *testing.T) { - m := &objects.TypeRegistry{} - s := objects.NewSequentialSchedule(m, nil) - assert.NotNil(t, s, "Scheduler should not be nil") - - var task interfaces.Task - - s.Schedule(5, 15, task) - s.Schedule(4, 6, task) - s.Schedule(6, 14, task) - s.Schedule(14, 16, task) - s.Schedule(4, 16, task) - - assert.Equal(t, 1, s.Length()) -} - -func TestFailSchedule2(t *testing.T) { +func TestScheduler_FailSchedule2(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -107,34 +91,7 @@ func TestFailSchedule2(t *testing.T) { assert.Nil(t, err) } -func TestFailSchedule3(t *testing.T) { - m := &objects.TypeRegistry{} - s := objects.NewSequentialSchedule(m, nil) - assert.NotNil(t, s, "Scheduler should not be nil") - - var err error - var task interfaces.Task - - s.Schedule(7, 15, task) - - s.Schedule(15, 17, task) - - assert.Nil(t, err) - - s.Schedule(15, 21, task) - - assert.NotNil(t, err) - - s.Schedule(1, 7, task) - - assert.Nil(t, err) - - s.Schedule(1, 8, task) - - assert.NotNil(t, err) -} - -func TestFind(t *testing.T) { +func TestScheduler_Find(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -163,7 +120,7 @@ func TestFind(t *testing.T) { } -func TestFailFind(t *testing.T) { +func TestScheduler_FailFind(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -176,7 +133,7 @@ func TestFailFind(t *testing.T) { assert.Equal(t, objects.ErrNothingScheduled, err) } -func TestFailFind2(t *testing.T) { +func TestScheduler_FailFind2(t *testing.T) { m := &objects.TypeRegistry{} s := objects.NewSequentialSchedule(m, nil) assert.NotNil(t, s, "Scheduler should not be nil") @@ -189,7 +146,7 @@ func TestFailFind2(t *testing.T) { assert.Equal(t, objects.ErrNothingScheduled, err) } -func TestRemove(t *testing.T) { +func TestScheduler_Remove(t *testing.T) { acct := accounts.Account{} state := objects.NewDkgState(acct) task := dkgtasks.NewPlaceHolder(state) @@ -206,7 +163,7 @@ func TestRemove(t *testing.T) { assert.Equal(t, 0, s.Length()) } -func TestFailRemove(t *testing.T) { +func TestScheduler_FailRemove(t *testing.T) { acct := accounts.Account{} state := objects.NewDkgState(acct) task := dkgtasks.NewPlaceHolder(state) @@ -227,7 +184,7 @@ func TestFailRemove(t *testing.T) { assert.Equal(t, 1, s.Length()) } -func TestRetreive(t *testing.T) { +func TestScheduler_Retreive(t *testing.T) { acct := accounts.Account{} state := objects.NewDkgState(acct) task := dkgtasks.NewPlaceHolder(state) @@ -243,7 +200,7 @@ func TestRetreive(t *testing.T) { assert.Nil(t, err) } -func TestFailRetrieve(t *testing.T) { +func TestScheduler_FailRetrieve(t *testing.T) { acct := accounts.Account{} state := objects.NewDkgState(acct) task := dkgtasks.NewPlaceHolder(state) @@ -259,7 +216,7 @@ func TestFailRetrieve(t *testing.T) { assert.Equal(t, objects.ErrNotScheduled, err) } -func TestMarshal(t *testing.T) { +func TestScheduler_Marshal(t *testing.T) { task := &adminTaskMock{} m := &objects.TypeRegistry{} m.RegisterInstanceType(&objects.Block{}) diff --git a/blockchain/objects/state_test.go b/blockchain/objects/state_test.go index cd2391a2..bbedc280 100644 --- a/blockchain/objects/state_test.go +++ b/blockchain/objects/state_test.go @@ -1,60 +1,61 @@ package objects_test -// import ( -// "testing" - -// "github.com/MadBase/MadNet/blockchain/objects" -// "github.com/stretchr/testify/assert" -// ) - -// func createState() *objects.MonitorState { - -// ms := &objects.MonitorState{ -// Version: 0, -// HighestBlockProcessed: 614, -// HighestBlockFinalized: 911, -// HighestEpochProcessed: 5, -// HighestEpochSeen: 10, -// LatestDepositProcessed: 1, -// LatestDepositSeen: 5, -// ValidatorSets: map[uint32]objects.ValidatorSet{}, -// Validators: map[uint32][]objects.Validator{614: {{Index: 7}}}, -// } - -// return ms -// } - -// func assertStateMatch(t *testing.T, ms *objects.MonitorState) { -// // Make sure the new struct looks like the old struct -// assert.Equal(t, uint64(614), ms.HighestBlockProcessed) -// assert.Equal(t, uint64(911), ms.HighestBlockFinalized) -// assert.Equal(t, uint32(5), ms.HighestEpochProcessed) -// assert.Equal(t, uint32(10), ms.HighestEpochSeen) -// assert.Equal(t, uint32(5), ms.HighestEpochProcessed) -// assert.Equal(t, uint32(1), ms.LatestDepositProcessed) -// assert.Equal(t, uint32(5), ms.LatestDepositSeen) - -// // -// assert.Equal(t, uint8(1), len(ms.Validators[614])) -// // assert.Equal(t, uint8(7), ms.Validators[614][0].Index) -// } - -// func TestBidirectionalJson(t *testing.T) { - -// // Build up a pseudo-realistic State instance -// ms := createState() - -// // Encode the test instance -// raw, err := json.Marshal(ms) -// assert.Nilf(t, err, "Should be no errors marshalling data") - -// t.Logf("raw:%v", string(raw)) - -// // Decode the bytes -// ms2 := &objects.MonitorState{} -// err = json.Unmarshal(raw, ms2) -// assert.Nilf(t, err, "Should be no errors unmarshalling data") - -// // Good? -// assertStateMatch(t, ms2) -// } +import ( + "encoding/json" + "testing" + + "github.com/MadBase/MadNet/blockchain/objects" + "github.com/stretchr/testify/assert" +) + +func createState() *objects.MonitorState { + + ms := &objects.MonitorState{ + Version: 0, + HighestBlockProcessed: 614, + HighestBlockFinalized: 911, + HighestEpochProcessed: 5, + HighestEpochSeen: 10, + LatestDepositProcessed: 1, + LatestDepositSeen: 5, + ValidatorSets: map[uint32]objects.ValidatorSet{}, + Validators: map[uint32][]objects.Validator{614: {{Index: 7}}}, + } + + return ms +} + +func assertStateMatch(t *testing.T, ms *objects.MonitorState) { + // Make sure the new struct looks like the old struct + assert.Equal(t, uint64(614), ms.HighestBlockProcessed) + assert.Equal(t, uint64(911), ms.HighestBlockFinalized) + assert.Equal(t, uint32(5), ms.HighestEpochProcessed) + assert.Equal(t, uint32(10), ms.HighestEpochSeen) + assert.Equal(t, uint32(5), ms.HighestEpochProcessed) + assert.Equal(t, uint32(1), ms.LatestDepositProcessed) + assert.Equal(t, uint32(5), ms.LatestDepositSeen) + + // + assert.Equal(t, 1, len(ms.Validators[614])) + // assert.Equal(t, uint8(7), ms.Validators[614][0].Index) +} + +func TestBidirectionalJson(t *testing.T) { + + // Build up a pseudo-realistic State instance + ms := createState() + + // Encode the test instance + raw, err := json.Marshal(ms) + assert.Nilf(t, err, "Should be no errors marshalling data") + + t.Logf("raw:%v", string(raw)) + + // Decode the bytes + ms2 := &objects.MonitorState{} + err = json.Unmarshal(raw, ms2) + assert.Nilf(t, err, "Should be no errors unmarshalling data") + + // Good? + assertStateMatch(t, ms2) +} diff --git a/blockchain/selectors_test.go b/blockchain/selectors_test.go index 93dde106..ec6b35d6 100644 --- a/blockchain/selectors_test.go +++ b/blockchain/selectors_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestSelector(t *testing.T) { +func TestSelector_Selector(t *testing.T) { sm := blockchain.NewSelectorMap() selector := sm.Selector("fdsfds") @@ -17,7 +17,7 @@ func TestSelector(t *testing.T) { assert.NotEqual(t, []byte{0, 0, 0, 0}, selector) } -func TestSignature(t *testing.T) { +func TestSelector_Signature(t *testing.T) { sm := blockchain.NewSelectorMap() testSig := "fdsfds" @@ -29,7 +29,7 @@ func TestSignature(t *testing.T) { assert.Equal(t, testSig, signature) } -func TestConcurrency(t *testing.T) { +func TestSelector_Concurrency(t *testing.T) { sm := blockchain.NewSelectorMap() iter := 10000 diff --git a/blockchain/staking_test.go b/blockchain/staking_test.go deleted file mode 100644 index e4621d73..00000000 --- a/blockchain/staking_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package blockchain_test - -/* -import ( - "context" - "math/big" - "testing" - - "github.com/MadBase/MadNet/blockchain/interfaces" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -type StakingTestSuite struct { - suite.Suite - eth interfaces.Ethereum - callOpts *bind.CallOpts - txnOpts *bind.TransactOpts -} - -var InitialAllowance = big.NewInt(1000000000000000000) - -func (s *StakingTestSuite) SetupTest() { - t := s.T() - var err error - s.eth, err = setupEthereum(t, 4) - assert.Nil(t, err) - eth := s.eth - c := s.eth.Contracts() - ctx := context.TODO() - - acct := eth.GetDefaultAccount() - txnOpts, _ := eth.GetTransactionOpts(ctx, eth.GetDefaultAccount()) - _, err = c.StakingToken().Transfer(txnOpts, acct.Address, InitialAllowance) - assert.Nilf(t, err, "Initial transfer of %v to %v failed: %v", InitialAllowance, acct.Address.Hex(), err) - - // Tester needs to approve those for Staking - s.txnOpts, err = eth.GetTransactionOpts(ctx, acct) - assert.Nil(t, err, "Can't build txnOpts") - - _, err = c.StakingToken().Approve(s.txnOpts, c.ValidatorsAddress(), InitialAllowance) - assert.Nilf(t, err, "Initial approval of %v to %v failed: %v", InitialAllowance, c.ValidatorsAddress().Hex(), err) - s.eth.Commit() - - s.callOpts = eth.GetCallOpts(ctx, acct) - - // Tell staking we're in the 1st epoch - _, err = c.Snapshots().SetEpoch(txnOpts, big.NewInt(1)) // Must be deploy account - assert.Nil(t, err) - s.eth.Commit() -} - -func (s *StakingTestSuite) TestStakeEvent() { - t := s.T() - - eth := s.eth - c := eth.Contracts() - - balance, err := c.Staking().BalanceStake(s.callOpts) - assert.Truef(t, err == nil, "Failed to check balance:%v", err) - assert.Truef(t, big.NewInt(10).Cmp(balance) > 0, "Allowance %v insufficient", balance) - - stakeAmount := big.NewInt(1000000) - txn, err := c.Staking().LockStake(s.txnOpts, stakeAmount) - assert.Nil(t, err, "Failed to post stake") - assert.NotNil(t, txn, "Staking transaction is nil") - s.eth.Commit() - - rcpt, err := eth.Queue().QueueAndWait(context.Background(), txn) - assert.True(t, err == nil, "Couldn't parse event log:%v", err) - - events := rcpt.Logs - assert.Equal(t, 2, len(events), "Should be 2 events.") - - foundStakeEvent := false - for _, event := range events { - stakeEvent, err := c.Staking().ParseLockedStake(*event) - if err == nil { - foundStakeEvent = true - assert.Equal(t, stakeAmount, stakeEvent.Amount, "Stake amount incorrect") - } - } - assert.True(t, foundStakeEvent) -} - -func (s *StakingTestSuite) TestUnlocked() { - stakeAmount := big.NewInt(1000000) - - t := s.T() - eth := s.eth - c := eth.Contracts() - ctx := context.TODO() - - // Start by making sure unlocked balance and stake are both 0 - unlocked, err := c.Staking().BalanceUnlocked(s.callOpts) - assert.Truef(t, err == nil, "Failed to get unlocked balance: %v", err) - assert.Truef(t, big.NewInt(0).Cmp(unlocked) == 0, "Initial unlocked balance should be 0 but is %v", unlocked) - s.eth.Commit() - - staked, err := c.Staking().BalanceStake(s.callOpts) - assert.Truef(t, err == nil, "Failed to get stake balance: %v", err) - assert.Truef(t, big.NewInt(0).Cmp(staked) == 0, "Initial stake should be 0 but is %v", staked) - s.eth.Commit() - - // Now we lock some - this pulls from token balance based on approvals - _, err = c.Staking().LockStake(s.txnOpts, stakeAmount) - assert.True(t, err == nil, "Failed to post stake:%v", err) - s.eth.Commit() - - // Make sure stake shows the increase and unlocked balance has no change - staked, err = c.Staking().BalanceStake(s.callOpts) - assert.Truef(t, err == nil, "Failed to get stake balance: %v", err) - assert.Truef(t, stakeAmount.Cmp(staked) == 0, "Stake should be %v but is %v", stakeAmount, staked) - t.Logf("staked balance is %v", staked) - - unlocked, err = c.Staking().BalanceUnlocked(s.callOpts) - assert.Truef(t, err == nil, "Failed to get unlocked balance: %v", err) - assert.Truef(t, big.NewInt(0).Cmp(unlocked) == 0, "Unlocked balance should be 0 but is %v", unlocked) - t.Logf("unlocked balance is %v", unlocked) - - // Request stake be unlockable - _, err = c.Staking().RequestUnlockStake(s.txnOpts) - assert.Truef(t, err == nil, "Failed to request unlock of stake: %v", err) - s.eth.Commit() - - // Set clock ahead - requires privileged account (contract owner/operator) - ownerAuth, _ := eth.GetTransactionOpts(ctx, eth.GetDefaultAccount()) - _, err = c.Snapshots().SetEpoch(ownerAuth, big.NewInt(5)) - assert.Truef(t, err == nil, "Failed to set clock forward: %v", err) - s.eth.Commit() - - // Now we can actually unlock stake - txn, err := c.Staking().UnlockStake(s.txnOpts, stakeAmount) - assert.Truef(t, err == nil, "Failed to unlock stake: %v", err) - s.eth.Commit() - - // Just making sure the unlock completes - _, err = eth.Queue().QueueAndWait(context.Background(), txn) - if err != nil { - t.Fatal(err) - } - // Now unlocked balance contains what was formerly staked - unlocked, err = c.Staking().BalanceUnlocked(s.callOpts) - assert.Truef(t, err == nil, "Failed to get stake balance: %v", err) - assert.Truef(t, stakeAmount.Cmp(unlocked) == 0, "Unlocked balance should be %v but is %v", stakeAmount, unlocked) -} - -func (s *StakingTestSuite) TestBalanceUnlockedFor() { - t := s.T() - eth := s.eth - c := eth.Contracts() - - balance, err := c.Staking().BalanceUnlockedFor(s.callOpts, c.ValidatorsAddress()) - assert.Nilf(t, err, "Failed: balanceUnlockedFor()") - assert.Truef(t, big.NewInt(0).Cmp(balance) == 0, "Allowance initially should be %v but is %v", InitialAllowance, balance) -} - -func TestStakingTestSuite(t *testing.T) { - suite.Run(t, new(StakingTestSuite)) -} -*/ diff --git a/blockchain/validators_test.go b/blockchain/validators_test.go deleted file mode 100644 index c3f1386d..00000000 --- a/blockchain/validators_test.go +++ /dev/null @@ -1,329 +0,0 @@ -package blockchain_test - -/* -import ( - "bufio" - "context" - "encoding/hex" - "fmt" - "os" - "testing" - - "github.com/MadBase/MadNet/consensus/objs" - "github.com/MadBase/MadNet/crypto" - "github.com/MadBase/MadNet/crypto/bn256" - "github.com/MadBase/MadNet/crypto/bn256/cloudflare" - "github.com/stretchr/testify/assert" -) - -const SnapshotTakenSelector string = "0x6d438b6b835d16cdae6efdc0259fdfba17e6aa32dae81863a2467866f85f724a" - -func TestSnapshot(t *testing.T) { - rawBlockHeaderString := "" + - "000000000000030008000000010004005900000002060000b500000002000000" + - "2a000000004000000d0000000201000019000000020100002500000002010000" + - "31000000020100007e06a605256de00205be97e3db46a7179d10baa270991a68" + - "82adff2b3ca99d37c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b" + - "7bfad8045d85a470000000000000000000000000000000000000000000000000" + - "00000000000000007682aa2f2a0cacceb6abbb88b081b76481dd2704ceb42194" + - "bb4d7aa8e41759110a1673b5fb0848a5fea6fb60aa3d013df90d1797f8b5511c" + - "242f1c4060cbf32512443fa842e474f906eb7aedbff7a2a20818b277ef9e9fed" + - "bae4d4012cdd476021b1d4a7f125e9199e945f602942928ccebfe5f76822bce2" + - "c25b05da413cf9431097b5fc8ed39f381362375f1de1680cdd0525c59a76959b" + - "b91deac7590ecdd12686f605b19f284323f20d30a2b1aa5333f7471acc3787a1" + - "c9b24fed41717ba612f6f612c92fdee07fd6636ed067a0262971ace406b1242a" + - "7c41397d34b642ed" - - // Just make sure it unmarshals as expected - rawBlockHeader, err := hex.DecodeString(rawBlockHeaderString) - assert.Nil(t, err) - assert.Equal(t, 392, len(rawBlockHeader)) - - t.Logf("rawBlockHeader: %x", rawBlockHeader) - - blockHeader := &objs.BlockHeader{} - err = blockHeader.UnmarshalBinary(rawBlockHeader) - if err != nil { - t.Fatal(err) - } - assert.Equal(t, uint32(42), blockHeader.BClaims.ChainID) - assert.Equal(t, uint32(16384), blockHeader.BClaims.Height) - assert.Equal(t, uint32(0), blockHeader.BClaims.TxCount) - - // pull out the block claims - bclaims := blockHeader.BClaims - rawBclaims, err := bclaims.MarshalBinary() - assert.Nil(t, err) - t.Logf("rawBclaims: %x", rawBclaims) - - // pull out the sig - rawSigGroup := blockHeader.SigGroup - assert.Equal(t, rawSigGroup, rawSigGroup) - - publicKeyG2, signatureG1, err := cloudflare.UnmarshalSignature(rawSigGroup) - assert.Nil(t, err) - - publicKey, err := bn256.G2ToBigIntArray(publicKeyG2) - assert.Nil(t, err) - - for idx := 0; idx < 4; idx++ { - t.Logf("publicKey[%d]: %x", idx, publicKey[idx]) - } - - signature, err := bn256.G1ToBigIntArray(signatureG1) - assert.Nil(t, err) - - for idx := 0; idx < 2; idx++ { - t.Logf("signature[%d]: %x", idx, signature[idx]) - } - - fmt.Printf("rawBclaims: %x\n", rawBclaims) - bhsh := crypto.Hasher(rawBclaims) - // fmt.Printf("blockHash: %x", ) - assert.Nil(t, err) - - ok, err := cloudflare.Verify(bhsh, signatureG1, publicKeyG2, cloudflare.HashToG1) - assert.Nil(t, err) - assert.True(t, ok) - - // Check validity with Crypto - eth, err := setupEthereum(t, 4) - assert.Nil(t, err) - - c := eth.Contracts() - ctx := context.TODO() - acct := eth.GetDefaultAccount() - callOpts := eth.GetCallOpts(ctx, acct) - txnOpts, err := eth.GetTransactionOpts(ctx, acct) - assert.Nil(t, err) - - good, err := c.Crypto().Verify(callOpts, bhsh, signature, publicKey) - assert.Nil(t, err) - assert.True(t, good) - - txn, err := c.Validators().Snapshot(txnOpts, rawSigGroup, rawBclaims) - assert.Nil(t, err) - assert.NotNil(t, txn) - eth.Commit() - - rcpt, err := eth.Queue().QueueAndWait(context.Background(), txn) - assert.Nil(t, err) - assert.Equal(t, uint64(1), rcpt.Status) - - // Look for the snapshot taken event - foundIt := false - for _, log := range rcpt.Logs { - if log.Topics[0].String() == SnapshotTakenSelector { - snapshotTaken, err := c.Validators().ParseSnapshotTaken(*log) - assert.Nil(t, err) - assert.Equal(t, uint64(1), snapshotTaken.Epoch.Uint64()) - foundIt = true - - // Now see if I can reconstruct the header from what we have - rawEventBclaims, err := c.Validators().GetRawBlockClaimsSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - rawEventSigGroup, err := c.Validators().GetRawSignatureSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - assert.Equal(t, rawBclaims, rawEventBclaims) - assert.Equal(t, rawSigGroup, rawEventSigGroup) - - bclaims := &objs.BClaims{} - err = bclaims.UnmarshalBinary(rawEventBclaims) - if err != nil { - t.Fatal(err) - } - header := &objs.BlockHeader{} - header.BClaims = bclaims - header.SigGroup = rawEventSigGroup - - assert.Equal(t, uint32(42), header.BClaims.ChainID) - assert.Equal(t, uint32(16384), header.BClaims.Height) - assert.Equal(t, uint32(0), header.BClaims.TxCount) - } - } - assert.True(t, foundIt, "Should have received SnapshotTaken event") -} - -func TestBlockHeaderParsing(t *testing.T) { - rawBlockHeaderString := "" + - "000000000000030008000000010004005900000002060000b500000002000000" + - "2a000000004000000d0000000201000019000000020100002500000002010000" + - "31000000020100007e06a605256de00205be97e3db46a7179d10baa270991a68" + - "82adff2b3ca99d37c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b" + - "7bfad8045d85a470000000000000000000000000000000000000000000000000" + - "00000000000000007682aa2f2a0cacceb6abbb88b081b76481dd2704ceb42194" + - "bb4d7aa8e41759110a1673b5fb0848a5fea6fb60aa3d013df90d1797f8b5511c" + - "242f1c4060cbf32512443fa842e474f906eb7aedbff7a2a20818b277ef9e9fed" + - "bae4d4012cdd476021b1d4a7f125e9199e945f602942928ccebfe5f76822bce2" + - "c25b05da413cf9431097b5fc8ed39f381362375f1de1680cdd0525c59a76959b" + - "b91deac7590ecdd12686f605b19f284323f20d30a2b1aa5333f7471acc3787a1" + - "c9b24fed41717ba612f6f612c92fdee07fd6636ed067a0262971ace406b1242a" + - "7c41397d34b642ed" - - // Convert the string to binary and make a copy for comparison later - rawBlockHeader, err := hex.DecodeString(rawBlockHeaderString) - assert.Nil(t, err) - - clonedRawBlockHeader := make([]byte, len(rawBlockHeader)) - copy(clonedRawBlockHeader, rawBlockHeader) - - // Just make sure it unmarshals as expected - blockHeader := &objs.BlockHeader{} - err = blockHeader.UnmarshalBinary(rawBlockHeader) - if err != nil { - t.Fatal(err) - } - assert.Equal(t, uint32(42), blockHeader.BClaims.ChainID) - assert.Equal(t, uint32(16384), blockHeader.BClaims.Height) - assert.Equal(t, uint32(0), blockHeader.BClaims.TxCount) - - // Make sure unmarshal->marshal is identical - bh, err := blockHeader.MarshalBinary() - assert.Nil(t, err) - for idx := 0; idx < 392; idx++ { - assert.Equal(t, rawBlockHeader[idx], bh[idx]) - } - - // see what changes - blockHeader.BClaims.ChainID = 42 - // blockHeader.BClaims.Height = 0x12345678 - // blockHeader.BClaims.TxCount = 0 - - bh, err = blockHeader.MarshalBinary() - assert.Nil(t, err) - - // what changed? - differences := make(map[int]string) - - for idx := 0; idx < 392; idx++ { - a := clonedRawBlockHeader[idx] - b := bh[idx] - if a != b { - differences[idx] = fmt.Sprintf("{0x%02x -> 0x%02x}", a, b) - } - } - t.Logf("Change count: %v", len(differences)) - t.Logf(" Changes: %v", differences) -} - -func TestBulkProcessBlockHeaders(t *testing.T) { - file, err := os.Open("../assets/test/blockheaders.txt") - assert.Nil(t, err) - - defer file.Close() - - scanner := bufio.NewScanner(file) - - for scanner.Scan() { - - hexText := scanner.Text() - rawBlockHeader, err := hex.DecodeString(hexText) - assert.Nil(t, err) - - processBlockHeader(t, rawBlockHeader) - } -} - -func processBlockHeader(t *testing.T, rawBlockHeader []byte) { - - blockHeader := &objs.BlockHeader{} - err := blockHeader.UnmarshalBinary(rawBlockHeader) - assert.Nil(t, err) - - // pull out the block claims - bclaims := blockHeader.BClaims - rawBclaims, err := bclaims.MarshalBinary() - assert.Nil(t, err) - bclaimsHash := crypto.Hasher(rawBclaims) - - // pull out the sig - rawSigGroup := blockHeader.SigGroup - - publicKeyG2, signatureG1, err := cloudflare.UnmarshalSignature(rawSigGroup) - assert.Nil(t, err) - - ok, err := cloudflare.Verify(bclaimsHash, signatureG1, publicKeyG2, cloudflare.HashToG1) - assert.Nil(t, err) - assert.True(t, ok, "verify should return true") - - // Check validity with Crypto - assert.Nil(t, err) - - eth, err := setupEthereum(t, 5) - assert.Nil(t, err) - c := eth.Contracts() - ctx := context.TODO() - acct := eth.GetDefaultAccount() - callOpts := eth.GetCallOpts(ctx, acct) - txnOpts, err := eth.GetTransactionOpts(ctx, acct) - assert.Nil(t, err) - - // Convert from G1/G2 into []*big.Int's - publicKey, err := bn256.G2ToBigIntArray(publicKeyG2) - assert.Nil(t, err) - - signature, err := bn256.G1ToBigIntArray(signatureG1) - assert.Nil(t, err) - - good, err := c.Crypto().Verify(callOpts, bclaimsHash, signature, publicKey) - assert.Nil(t, err) - assert.True(t, good) - - t.Logf("rawBclaims: 0x%x", rawBclaims) - - txn, err := c.Validators().Snapshot(txnOpts, rawSigGroup, rawBclaims) - assert.Nil(t, err) - assert.NotNil(t, txn) - eth.Commit() - - rcpt, err := eth.Queue().QueueAndWait(context.Background(), txn) - assert.Nil(t, err) - assert.Equal(t, uint64(1), rcpt.Status) - - // Look for the snapshot taken event - foundIt := false - for _, log := range rcpt.Logs { - if log.Topics[0].String() == SnapshotTakenSelector { - snapshotTaken, err := c.Validators().ParseSnapshotTaken(*log) - assert.Nil(t, err) - assert.Equal(t, uint64(1), snapshotTaken.Epoch.Uint64()) - foundIt = true - - // Now see if I can reconstruct the header from what we have - rawEventBclaims, err := c.Validators().GetRawBlockClaimsSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - rawEventSigGroup, err := c.Validators().GetRawSignatureSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - chainId, err := c.Validators().GetChainIdFromSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - height, err := c.Validators().GetMadHeightFromSnapshot(callOpts, snapshotTaken.Epoch) - assert.Nil(t, err) - - assert.Equal(t, rawBclaims, rawEventBclaims) - assert.Equal(t, rawSigGroup, rawEventSigGroup) - - bclaims := &objs.BClaims{} - err = bclaims.UnmarshalBinary(rawEventBclaims) - assert.Nil(t, err) - - header := &objs.BlockHeader{} - header.BClaims = bclaims - header.SigGroup = rawEventSigGroup - - t.Logf("ChainID:%v Height:%v TxCount:%v", bclaims.ChainID, bclaims.Height, bclaims.TxCount) - - assert.Equal(t, blockHeader.BClaims.ChainID, chainId, "ChainID isn't as expected") - assert.Equal(t, blockHeader.BClaims.Height, height, "Height isn't as expected") - assert.Equal(t, blockHeader.BClaims.ChainID, header.BClaims.ChainID) - assert.Equal(t, blockHeader.BClaims.Height, header.BClaims.Height) - assert.Equal(t, blockHeader.BClaims.TxCount, header.BClaims.TxCount) - } - } - assert.True(t, foundIt, "Should have received SnapshotTaken event") -} -*/ diff --git a/bridge/scripts/lib/alicenetTasks.ts b/bridge/scripts/lib/alicenetTasks.ts index c1e96c52..9a6d0d3e 100644 --- a/bridge/scripts/lib/alicenetTasks.ts +++ b/bridge/scripts/lib/alicenetTasks.ts @@ -185,6 +185,7 @@ task( }); task("registerValidators", "registers validators") + .addFlag("test") .addParam("factoryAddress", "address of the factory deploying the contract") .addVariadicPositionalParam( "addresses", @@ -219,7 +220,14 @@ task("registerValidators", "registers validators") ) .connect(admin) .deploy(taskArgs.factoryAddress); - await registrationContract.deployTransaction.wait(3); + + if (taskArgs.test) { + await hre.network.provider.send("hardhat_mine", [ + hre.ethers.utils.hexValue(3), + ]); + } else { + await registrationContract.deployTransaction.wait(3); + } const validatorPool = await hre.ethers.getContractAt( "ValidatorPool", @@ -229,25 +237,34 @@ task("registerValidators", "registers validators") ); console.log(`validatorPool Address: ${validatorPool.address}`); console.log("Staking validators"); - await ( - await factory.delegateCallAny( - registrationContract.address, - registrationContract.interface.encodeFunctionData("stakeValidators", [ - validatorAddresses.length, - ]) - ) - ).wait(3); + let tx = await factory.delegateCallAny( + registrationContract.address, + registrationContract.interface.encodeFunctionData("stakeValidators", [ + validatorAddresses.length, + ]) + ); + if (taskArgs.test) { + await hre.network.provider.send("hardhat_mine", [ + hre.ethers.utils.hexValue(3), + ]); + } else { + await tx.wait(3); + } console.log("Registering validators"); - await ( - await factory.delegateCallAny( - registrationContract.address, - registrationContract.interface.encodeFunctionData( - "registerValidators", - [validatorAddresses] - ) - ) - ).wait(3); + tx = await factory.delegateCallAny( + registrationContract.address, + registrationContract.interface.encodeFunctionData("registerValidators", [ + validatorAddresses, + ]) + ); + if (taskArgs.test) { + await hre.network.provider.send("hardhat_mine", [ + hre.ethers.utils.hexValue(3), + ]); + } else { + await tx.wait(3); + } console.log("done"); }); diff --git a/scripts/base-scripts/ethdkg.sh b/scripts/base-scripts/ethdkg.sh index b6d44b68..22b75311 100755 --- a/scripts/base-scripts/ethdkg.sh +++ b/scripts/base-scripts/ethdkg.sh @@ -18,4 +18,4 @@ fi npx hardhat --network "$NETWORK" --show-stack-traces initializeEthdkg --factory-address "$FACTORY_ADDRESS" -cd "$CURRENT_WD" \ No newline at end of file +cd "$CURRENT_WD" diff --git a/scripts/base-scripts/hardhat_node.sh b/scripts/base-scripts/hardhat_node.sh index 446369c4..c705889f 100755 --- a/scripts/base-scripts/hardhat_node.sh +++ b/scripts/base-scripts/hardhat_node.sh @@ -5,14 +5,11 @@ set -x CURRENT_WD=$PWD BRIDGE_DIR=./bridge -cd $BRIDGE_DIR +cd $BRIDGE_DIR || exit npx hardhat node --show-stack-traces & -GETH_PID="$!" - -trap "trap - SIGTERM && kill -- $GETH_PID" SIGTERM SIGINT SIGKILL EXIT - +trap 'pkill -9 -f hardhat' SIGTERM wait -cd $CURRENT_WD +cd "$CURRENT_WD" || exit diff --git a/scripts/base-scripts/register_test.sh b/scripts/base-scripts/register_test.sh index 9d3e6186..691c81f5 100755 --- a/scripts/base-scripts/register_test.sh +++ b/scripts/base-scripts/register_test.sh @@ -7,10 +7,6 @@ BRIDGE_DIR=./bridge cd $BRIDGE_DIR - -npx hardhat --network dev --show-stack-traces registerValidators --factory-address "$@" - +npx hardhat --network dev --show-stack-traces registerValidators --test --factory-address "$@" cd $CURRENT_WD - - diff --git a/scripts/main.sh b/scripts/main.sh index 5bdcfda3..e7642892 100755 --- a/scripts/main.sh +++ b/scripts/main.sh @@ -176,10 +176,7 @@ case $1 in ;; hardhat_node) ./scripts/base-scripts/hardhat_node.sh & - GETH_PID="$!" - - trap "trap - SIGTERM && kill -- $GETH_PID" SIGTERM SIGINT SIGKILL EXIT - + trap 'pkill -9 -f hardhat' SIGTERM wait ;; hardhat_local_node)