From 09446f5ebda1627e36c777c0f967f27f86e8a441 Mon Sep 17 00:00:00 2001 From: Fynn Date: Sat, 24 Mar 2018 18:37:53 +0100 Subject: [PATCH 01/30] WIP: SMC for phase 1 Former-commit-id: d756e5811f4d8803252276d83bc9e189473ed435 [formerly 3f9041a1733c9bb0882b395010008fe2aea5f74e] Former-commit-id: 3911cda4e088c50ba9a5d85e6a6af963c4773a91 --- sharding/contracts/sharding_manager.sol | 366 ++++++++++++------------ 1 file changed, 190 insertions(+), 176 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 11c282041..ab194ca17 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -1,35 +1,38 @@ pragma solidity ^0.4.19; contract SMC { - event TxToShard(address indexed to, int indexed shardId, int receiptId); - event CollationAdded(int indexed shardId, uint expectedPeriodNumber, - bytes32 periodStartPrevHash, bytes32 parentHash, - bytes32 transactionRoot, address coinbase, - bytes32 stateRoot, bytes32 receiptRoot, - int number, bool isNewHead, int score); + event HeaderAdded(uint indexed shard_id, bytes32 parent_hash, + bytes32 chunk_root, int128 period, int128 height, + address proposer_address, uint proposer_bid, + bytes proposer_signature); event Deposit(address collator, int index); event Withdraw(int index); + // Entry in collator_registry struct Collator { - // Amount of wei the collator holds - uint deposit; - // The collator's address - address addr; + // When collator asked for unregistration + uint deregistered; + // The collator's pool index + int pool_index; + } + + // Entry in proposer_registry + struct Proposer { + // Shard id of the deposit + uint shardId; + // Deposit in ether in each shard + uint[] deposit; } struct CollationHeader { - bytes32 parentHash; - int score; - } - - struct Receipt { - int shardId; - uint txStartgas; - uint txGasprice; - uint value; - bytes32 data; - address sender; - address to; + uint256 shard_id; // pointer to shard + bytes32 parent_hash; // pointer to parent header + bytes32 chunk_root; // pointer to collation body + int128 period; // Period which header should be included + int128 height; // Collation's height + address proposer_address; // Proposer's address + uint256 proposer_bid; // Proposer's bid + bytes proposer_signature; // Proposer's signature } // Packed variables to be used in addHeader @@ -41,36 +44,55 @@ contract SMC { } // collatorId => Collators - mapping (int => Collator) public collators; + // mapping (int => Collator) public collators; + address[] public collator_pool; + // proposerId => Proposer + // mapping (int => Proposer) public proposers; + Proposer[] public proposer_pool; + + // Collator registry (deregistered is 0 for not yet deregistered collators) + mapping (address => Collator) public collator_registry; + mapping (address => Proposer) public proposer_registry; + // shard_id => (header_hash => tree root) + mapping (uint => mapping (bytes32 => bytes32)) public collation_trees; // shardId => (headerHash => CollationHeader) mapping (int => mapping (bytes32 => CollationHeader)) public collationHeaders; - // receiptId => Receipt - mapping (int => Receipt) public receipts; // shardId => headerHash - mapping (int => bytes32) shardHead; + mapping (int => bytes32) shardead; // Number of collators - int public numCollators; - // Number of receipts - int numReceipts; - // Indexs of empty slots caused by the function `withdraw` - mapping (int => int) emptySlotsStack; + int public collator_pool_len; + // Indexes of empty slots caused by the function `withdraw` + int[] empty_slots_stack; // The top index of the stack in empty_slots_stack - int emptySlotsStackTop; + int empty_slots_stack_top; // Has the collator deposited before? - mapping (address => bool) public isCollatorDeposited; + mapping (address => bool) public is_collator_deposited; // Constant values - uint constant periodLength = 5; - int constant public shardCount = 100; - // The exact deposit size which you have to deposit to become a collator - uint constant depositSize = 100 ether; + uint constant PERIOD_LENGTH = 5; + // Exact collation body size (1mb) + uint constant COLLATION_SIZE = 2 ** 20; + // Subsidy in vEth + uint constant COLLATOR_SUBSIDY = 0.001 ether; + // Number of shards + int constant SHARD_COUNT = 100; + // The minimum deposit size for a collator + uint constant COLLATOR_DEPOSIT = 1000 ether; + // The minimum deposit size for a proposer + uint constant PROPOSER_DEPOSIT = 1 ether; + // The minimum balance of a proposer (for collators) + uint constant MIN_PROPOSER_BALANCE = 0.1 ether; + // Time the ether is locked by collators + uint constant COLLATOR_LOCKUP_LENGTH = 16128; + // Time the ether is locked by proposers + uint constant PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract // is able to return the collator of that period - uint constant lookAheadPeriods = 4; + uint constant LOOKAHEAD_LENGTH = 4; // Log the latest period number of the shard - mapping (int => int) public periodHead; + mapping (int => int) public period_head; function SMC() public { } @@ -84,170 +106,162 @@ contract SMC { // Uses a block hash as a seed to pseudorandomly select a signer from the collator pool. // [TODO] Chance of being selected should be proportional to the collator's deposit. // Should be able to return a value for the current period or any future period up to. - function getEligibleCollator(int _shardId, uint _period) public view returns(address) { - require(_period >= lookAheadPeriods); - require((_period - lookAheadPeriods) * periodLength < block.number); - require(numCollators > 0); + function get_eligible_collator(uint256 shard_id, uint256 period) public view returns(address) { + require(period >= LOOKAHEAD_LENGTH); + require((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH < block.number); + require(collator_pool_len > 0); // [TODO] Should check further if this safe or not - return collators[ - int( - uint( - keccak256( - uint(block.blockhash((_period - lookAheadPeriods) * periodLength)), - _shardId - ) - ) % - uint(getCollatorsMaxIndex()) - ) - ].addr; + return collator_pool[ + uint( + keccak256( + uint(block.blockhash((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH)), + shard_id + ) + ) % + uint(collator_pool_len) + ]; } - function deposit() public payable returns(int) { - require(!isCollatorDeposited[msg.sender]); - require(msg.value == depositSize); - // Find the empty slot index in collators pool + function compute_header_hash(uint256 shard_id, + bytes32 parent_hash, + bytes32 chunk_root, + uint256 period, + address proposer_address, + uint256 proposer_bid) public returns(bytes32){ + + } + + function register_collator() public payable returns(int) { + address collator_address = msg.sender; + require(!is_collator_deposited[msg.sender]); + require(msg.value == COLLATOR_DEPOSIT); + + is_collator_deposited[msg.sender] = true; int index; - if (!isStackEmpty()) - index = stackPop(); - else - index = int(numCollators); - - collators[index] = Collator({ - deposit: msg.value, - addr: msg.sender - }); - ++numCollators; - isCollatorDeposited[msg.sender] = true; - - Deposit(msg.sender, index); + if (!empty_stack()) { + index = stack_pop(); + collator_pool[uint(index)] = collator_address; + } + else { + index = collator_pool_len; + collator_pool.push(collator_address); + } + ++collator_pool_len; + Deposit(collator_address, index); return index; } // Removes the collator from the collator pool and refunds the deposited ether - function withdraw(int _collatorIndex) public { - require(msg.sender == collators[_collatorIndex].addr); - // [FIXME] Should consider calling the collator's contract, might be useful - // when the collator is a contract. - collators[_collatorIndex].addr.transfer(collators[_collatorIndex].deposit); - isCollatorDeposited[collators[_collatorIndex].addr] = false; - delete collators[_collatorIndex]; - stackPush(_collatorIndex); - --numCollators; - Withdraw(_collatorIndex); + function deregister_collator(int index) public { + address collator_address = msg.sender; + require(is_collator_deposited[msg.sender]); + require(collator_pool[uint(index)] == collator_address); + + collator_registry[collator_address] = Collator({ + deregistered: block.number, + pool_index: index + }); + + stack_push(index); + --collator_pool_len; + // Withdraw(_collatorIndex); + } + + function release_collator() public { + + } + + function register_proposer() public payable returns(int) { + + } + + function deregister_proposer() public { + + } + + function release_proposer() public { + + } + + function proposer_add_balance(uint shard_id) payable public { + + } + + function proposer_withdraw_balance(uint shard_id) public { + } // Attempts to process a collation header, returns true on success, reverts on failure. - function addHeader(int _shardId, uint _expectedPeriodNumber, bytes32 _periodStartPrevHash, - bytes32 _parentHash, bytes32 _transactionRoot, - address _coinbase, bytes32 _stateRoot, bytes32 _receiptRoot, - int _number) public returns(bool) { - HeaderVars memory headerVars; + function addHeader(uint _shardId, uint period, bytes32 height, + bytes32 _parent_hash, bytes32 chunk_root, + address proposer_address, uint proposer_bid, + bytes proposer_signature) public returns(bool) { + // HeaderVars memory headerVars; - // Check if the header is valid - require((_shardId >= 0) && (_shardId < shardCount)); - require(block.number >= periodLength); - require(_expectedPeriodNumber == block.number / periodLength); - require(_periodStartPrevHash == block.blockhash(_expectedPeriodNumber * periodLength - 1)); + // // Check if the header is valid + // require((_shardId >= 0) && (_shardId < shardCount)); + // require(block.number >= periodLength); + // require(_expectedPeriodNumber == block.number / periodLength); + // require(_periodStartPrevHash == block.blockhash(_expectedPeriodNumber * periodLength - 1)); - // Check if this header already exists - headerVars.entireHeaderHash = keccak256(_shardId, _expectedPeriodNumber, _periodStartPrevHash, - _parentHash, _transactionRoot, bytes32(_coinbase), - _stateRoot, _receiptRoot, _number); - assert(collationHeaders[_shardId][headerVars.entireHeaderHash].score == 0); - // Check whether the parent exists. - // if (parent_collation_hash == 0), i.e., is the genesis, - // then there is no need to check. - if (_parentHash != 0x0) - assert(collationHeaders[_shardId][_parentHash].score > 0); - // Check if only one collation in one period - assert(periodHead[_shardId] < int(_expectedPeriodNumber)); + // // Check if this header already exists + // headerVars.entireHeaderHash = keccak256(_shardId, _expectedPeriodNumber, _periodStartPrevHash, + // _parentHash, _transactionRoot, bytes32(_coinbase), + // _stateRoot, _receiptRoot, _number); + // assert(collationHeaders[_shardId][headerVars.entireHeaderHash].score == 0); + // // Check whether the parent exists. + // // if (parent_collation_hash == 0), i.e., is the genesis, + // // then there is no need to check. + // if (_parentHash != 0x0) + // assert(collationHeaders[_shardId][_parentHash].score > 0); + // // Check if only one collation in one period + // assert(periodHead[_shardId] < int(_expectedPeriodNumber)); - // Check the signature with validation_code_addr - headerVars.collatorAddr = getEligibleCollator(_shardId, block.number/periodLength); - require(headerVars.collatorAddr != 0x0); - require(msg.sender == headerVars.collatorAddr); + // // Check the signature with validation_code_addr + // headerVars.collatorAddr = getEligibleCollator(_shardId, block.number/periodLength); + // require(headerVars.collatorAddr != 0x0); + // require(msg.sender == headerVars.collatorAddr); - // Check score == collationNumber - headerVars.score = collationHeaders[_shardId][_parentHash].score + 1; - require(_number == headerVars.score); + // // Check score == collationNumber + // headerVars.score = collationHeaders[_shardId][_parentHash].score + 1; + // require(_number == headerVars.score); - // Add the header - collationHeaders[_shardId][headerVars.entireHeaderHash] = CollationHeader({ - parentHash: _parentHash, - score: headerVars.score - }); + // // Add the header + // collationHeaders[_shardId][headerVars.entireHeaderHash] = CollationHeader({ + // parentHash: _parentHash, + // score: headerVars.score + // }); - // Update the latest period number - periodHead[_shardId] = int(_expectedPeriodNumber); + // // Update the latest period number + // periodHead[_shardId] = int(_expectedPeriodNumber); - // Determine the head - if (headerVars.score > collationHeaders[_shardId][shardHead[_shardId]].score) { - shardHead[_shardId] = headerVars.entireHeaderHash; - headerVars.isNewHead = true; - } + // // Determine the head + // if (headerVars.score > collationHeaders[_shardId][shardHead[_shardId]].score) { + // shardHead[_shardId] = headerVars.entireHeaderHash; + // headerVars.isNewHead = true; + // } - CollationAdded(_shardId, _expectedPeriodNumber, _periodStartPrevHash, - _parentHash, _transactionRoot, _coinbase, _stateRoot, - _receiptRoot, _number, headerVars.isNewHead, headerVars.score); + // CollationAdded(_shardId, _expectedPeriodNumber, _periodStartPrevHash, + // _parentHash, _transactionRoot, _coinbase, _stateRoot, + // _receiptRoot, _number, headerVars.isNewHead, headerVars.score); - return true; + // return true; } - // Records a request to deposit msg.value ETH to address to in shard shard_id - // during a future collation. Saves a `receipt ID` for this request, - // also saving `msg.sender`, `msg.value`, `to`, `shard_id`, `startgas`, - // `gasprice`, and `data`. - function txToShard(address _to, int _shardId, uint _txStartgas, uint _txGasprice, - bytes12 _data) public payable returns(int) { - receipts[numReceipts] = Receipt({ - shardId: _shardId, - txStartgas: _txStartgas, - txGasprice: _txGasprice, - value: msg.value, - sender: msg.sender, - to: _to, - data: _data - }); - var receiptId = numReceipts; - ++numReceipts; - TxToShard(_to, _shardId, receiptId); - return receiptId; + function empty_stack() internal view returns(bool) { + return empty_slots_stack_top == 0; } - function updateGasPrice(int _receiptId, uint _txGasprice) public payable returns(bool) { - require(receipts[_receiptId].sender == msg.sender); - receipts[_receiptId].txGasprice = _txGasprice; - return true; + function stack_push(int index) internal { + empty_slots_stack[uint(empty_slots_stack_top)] = index; + ++empty_slots_stack_top; } - function isStackEmpty() internal view returns(bool) { - return emptySlotsStackTop == 0; - } - - function stackPush(int index) internal { - emptySlotsStack[emptySlotsStackTop] = index; - ++emptySlotsStackTop; - } - - function stackPop() internal returns(int) { - if (isStackEmpty()) + function stack_pop() internal returns(int) { + if (empty_stack()) return -1; - --emptySlotsStackTop; - return emptySlotsStack[emptySlotsStackTop]; - } - - function getCollatorsMaxIndex() internal view returns(int) { - int activateCollatorNum = 0; - int allCollatorSlotsNum = numCollators + emptySlotsStackTop; - - // TODO: any better way to iterate the mapping? - for (int i = 0; i < 1024; ++i) { - if (i >= allCollatorSlotsNum) - break; - if (collators[i].addr != 0x0) - activateCollatorNum += 1; - } - return activateCollatorNum + emptySlotsStackTop; + --empty_slots_stack_top; + return empty_slots_stack[uint(empty_slots_stack_top)]; } } From 7fa709bd406b83ad4a75b2dc12a5133c4919affe Mon Sep 17 00:00:00 2001 From: Fynn Date: Wed, 4 Apr 2018 07:57:06 +0200 Subject: [PATCH 02/30] sharding: collator functions deregister_collator and release_collator implementation Former-commit-id: 2c9a3ef1ee840209a65f9d6bd5d27f6efcad4ce0 [formerly f60bca0bc0a46f61dfa45fc62af9c37d75b6a749] Former-commit-id: 3be99e546546fbf91ffb92586dd9e4448b4b563c --- sharding/contracts/sharding_manager.sol | 95 ++++++++++++++----------- 1 file changed, 55 insertions(+), 40 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index ab194ca17..f6a8d0354 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -5,15 +5,21 @@ contract SMC { bytes32 chunk_root, int128 period, int128 height, address proposer_address, uint proposer_bid, bytes proposer_signature); - event Deposit(address collator, int index); - event Withdraw(int index); + event CollatorRegistered(address collator, uint pool_index); + event CollatorDeregistered(uint pool_index); + event CollatorReleased(uint pool_index); + event ProposerRegistered(uint pool_index); + event ProposerDeregistered(uint index); + event ProposerReleased(uint index); // Entry in collator_registry struct Collator { // When collator asked for unregistration uint deregistered; // The collator's pool index - int pool_index; + uint pool_index; + // False if collator has not deposited, true otherwise + bool deposited; } // Entry in proposer_registry @@ -61,13 +67,11 @@ contract SMC { mapping (int => bytes32) shardead; // Number of collators - int public collator_pool_len; + uint public collator_pool_len; // Indexes of empty slots caused by the function `withdraw` - int[] empty_slots_stack; + uint[] empty_slots_stack; // The top index of the stack in empty_slots_stack - int empty_slots_stack_top; - // Has the collator deposited before? - mapping (address => bool) public is_collator_deposited; + uint empty_slots_stack_top; // Constant values uint constant PERIOD_LENGTH = 5; @@ -76,7 +80,7 @@ contract SMC { // Subsidy in vEth uint constant COLLATOR_SUBSIDY = 0.001 ether; // Number of shards - int constant SHARD_COUNT = 100; + uint constant SHARD_COUNT = 100; // The minimum deposit size for a collator uint constant COLLATOR_DEPOSIT = 1000 ether; // The minimum deposit size for a proposer @@ -97,12 +101,6 @@ contract SMC { function SMC() public { } - // Returns the gas limit that collations can currently have (by default make - // this function always answer 10 million). - function getCollationGasLimit() public pure returns(uint) { - return 10000000; - } - // Uses a block hash as a seed to pseudorandomly select a signer from the collator pool. // [TODO] Chance of being selected should be proportional to the collator's deposit. // Should be able to return a value for the current period or any future period up to. @@ -118,7 +116,7 @@ contract SMC { shard_id ) ) % - uint(collator_pool_len) + collator_pool_len ]; } @@ -131,44 +129,57 @@ contract SMC { } - function register_collator() public payable returns(int) { + function register_collator() public payable returns(bool) { address collator_address = msg.sender; - require(!is_collator_deposited[msg.sender]); + require(!collator_registry[collator_address].deposited); require(msg.value == COLLATOR_DEPOSIT); - - is_collator_deposited[msg.sender] = true; - int index; + + uint index; if (!empty_stack()) { index = stack_pop(); - collator_pool[uint(index)] = collator_address; + collator_pool[index] = collator_address; } else { index = collator_pool_len; collator_pool.push(collator_address); } ++collator_pool_len; - Deposit(collator_address, index); - return index; + + collator_registry[collator_address] = Collator({ + deregistered: 0, + pool_index: index, + deposited: true + }); + CollatorRegistered(collator_address, index); + return true; } - // Removes the collator from the collator pool and refunds the deposited ether - function deregister_collator(int index) public { + // Removes the collator from the collator pool and sets deregistered period + function deregister_collator() public { address collator_address = msg.sender; - require(is_collator_deposited[msg.sender]); - require(collator_pool[uint(index)] == collator_address); + uint index = collator_registry[collator_address].pool_index; + // Check if collator deposited + require(collator_registry[collator_address].deposited); + require(collator_pool[index] == collator_address); - collator_registry[collator_address] = Collator({ - deregistered: block.number, - pool_index: index - }); + // Deregistered period + collator_registry[collator_address].deregistered = block.number / PERIOD_LENGTH; stack_push(index); --collator_pool_len; - // Withdraw(_collatorIndex); + CollatorDeregistered(index); } function release_collator() public { + address collator_address = msg.sender; + require(collator_registry[collator_address].deposited == true); + // Deregistered + require(collator_registry[collator_address].deregistered != 0); + // Locked up period + require((block.number / PERIOD_LENGTH) > (collator_registry[collator_address].deregistered + COLLATOR_LOCKUP_LENGTH)); + delete collator_registry[collator_address]; + collator_address.transfer(COLLATOR_DEPOSIT); } function register_proposer() public payable returns(int) { @@ -253,15 +264,19 @@ contract SMC { return empty_slots_stack_top == 0; } - function stack_push(int index) internal { - empty_slots_stack[uint(empty_slots_stack_top)] = index; + function stack_push(uint index) internal { + if (empty_slots_stack.length == empty_slots_stack_top) + empty_slots_stack.push(index); + else + empty_slots_stack[empty_slots_stack_top] = index; + ++empty_slots_stack_top; } - - function stack_pop() internal returns(int) { - if (empty_stack()) - return -1; + // Pop element from stack + // Caller should check if stack is empty + function stack_pop() internal returns(uint) { + require(empty_slots_stack_top > 1); --empty_slots_stack_top; - return empty_slots_stack[uint(empty_slots_stack_top)]; + return empty_slots_stack[empty_slots_stack_top]; } } From abdf7b9b9df6fdf42df892e40dd5ebe0edce8695 Mon Sep 17 00:00:00 2001 From: Fynn Date: Wed, 4 Apr 2018 07:57:45 +0200 Subject: [PATCH 03/30] sharding: tests for deregister_collator Former-commit-id: b45132122f5ff237082a390d04a9fce51098264c [formerly e75f76656887bac728ab65d60acc330adece44ba] Former-commit-id: aeea9a6841dffc722f171d2d10c166c8af523008 --- sharding/contracts/sharding_manager_test.go | 81 ++++++++++----------- 1 file changed, 38 insertions(+), 43 deletions(-) diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index b4bb9c3db..6f3c4d903 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -35,57 +35,41 @@ func TestContractCreation(t *testing.T) { } } -// Test getting the collation gas limit -func TestGetCollationGasLimit(t *testing.T) { - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - _, _, smc, _ := deploySMCContract(backend) - gasLimit, err := smc.GetCollationGasLimit(&bind.CallOpts{}) - if err != nil { - t.Fatalf("Error getting collationGasLimit: %v", err) - } - if gasLimit.Cmp(big.NewInt(10000000)) != 0 { - t.Fatalf("collation gas limit should be 10000000 gas") - } -} - -// Test collator deposit +// Test register collator func TestCollatorDeposit(t *testing.T) { backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) transactOpts := bind.NewKeyedTransactor(key) _, _, smc, _ := deploySMCContract(backend) - // Test deposit() function + // Test register_collator() function // Deposit 100 Eth transactOpts.Value = collatorDeposit - if _, err := smc.Deposit(transactOpts); err != nil { + if _, err := smc.Register_collator(transactOpts); err != nil { t.Fatalf("Collator cannot deposit: %v", err) } backend.Commit() // Check updated number of collators - numCollators, err := smc.NumCollators(&bind.CallOpts{}) + numCollators, err := smc.Collator_pool_len(&bind.CallOpts{}) if err != nil { - t.Fatalf("Failed to get number of collators: %v", err) + t.Fatalf("Failed to get collator pool length: %v", err) } if numCollators.Cmp(big.NewInt(1)) != 0 { t.Fatalf("Failed to update number of collators") } - // Check collator structure - collatorStruct, err := smc.Collators(&bind.CallOpts{}, big.NewInt(0)) + // Check deposited is true + tx, err := smc.Collator_registry(&bind.CallOpts{}, addr) if err != nil { - t.Fatalf("Failed to get collator structure: %v", err) + t.Fatalf("Failed to update collator registry: %v", err) } - if collatorStruct.Addr != addr { - t.Fatalf("Wrong collator address, %v should be %v", collatorStruct.Addr, addr) - } - if collatorStruct.Deposit.Cmp(collatorDeposit) != 0 { - t.Fatalf("Wrong collator deposit, %v should be %v", collatorStruct.Deposit, collatorDeposit) + if tx.Deposited != true { + t.Fatalf("Collator registry not updated") } - // Check for the Deposit event - depositsEventsIterator, err := smc.FilterDeposit(&bind.FilterOpts{}) + // Check for the RegisterCollator event + depositsEventsIterator, err := smc.FilterCollatorRegistered(&bind.FilterOpts{}) if err != nil { t.Fatalf("Failed to get Deposit event: %v", err) } @@ -95,36 +79,47 @@ func TestCollatorDeposit(t *testing.T) { if depositsEventsIterator.Event.Collator != addr { t.Fatalf("Collator address mismatch: %x should be %x", depositsEventsIterator.Event.Collator, addr) } - if depositsEventsIterator.Event.Index.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Collator index mismatch: %d should be 0", depositsEventsIterator.Event.Index) + if depositsEventsIterator.Event.Pool_index.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Collator index mismatch: %d should be 0", depositsEventsIterator.Event.Pool_index) } } -// Test collator withdraw +// Test collator withdraw from the pool func TestCollatorWithdraw(t *testing.T) { backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) transactOpts := bind.NewKeyedTransactor(key) _, _, smc, _ := deploySMCContract(backend) transactOpts.Value = collatorDeposit - smc.Deposit(transactOpts) + // Register collator + smc.Register_collator(transactOpts) transactOpts.Value = big.NewInt(0) - _, err := smc.Withdraw(transactOpts, big.NewInt(0)) - if err != nil { - t.Fatalf("Failed to withdraw: %v", err) - } + // Deregister collator + _, err := smc.Deregister_collator(transactOpts) backend.Commit() - - // Check for the Withdraw event - withdrawsEventsIterator, err := smc.FilterWithdraw(&bind.FilterOpts{Start: 0}) if err != nil { - t.Fatalf("Failed to get withdraw event: %v", err) + t.Fatalf("Failed to deregister collator: %v", err) + } + + // Check for the CollatorDeregistered event + withdrawsEventsIterator, err := smc.FilterCollatorDeregistered(&bind.FilterOpts{Start: 0}) + if err != nil { + t.Fatalf("Failed to get CollatorDeregistered event: %v", err) } if !withdrawsEventsIterator.Next() { - t.Fatal("No withdraw event found") + t.Fatal("No CollatorDeregistered event found") } - if withdrawsEventsIterator.Event.Index.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Collator index mismatch: %d should be 0", withdrawsEventsIterator.Event.Index) + if withdrawsEventsIterator.Event.Pool_index.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Collator index mismatch: %d should be 0", withdrawsEventsIterator.Event.Pool_index) } + // for i := 0; i < 16128*5+1; i++ { + // backend.Commit() + // } + + // Release collator + // _, err = smc.Release_collator(transactOpts) + // if err != nil { + // t.Fatalf("Failed to release collator: %v", err) + // } } From 46c33c9bfe01c3e38ad0b2e452bee8754b01a62f Mon Sep 17 00:00:00 2001 From: Fynn Date: Wed, 4 Apr 2018 18:05:10 +0200 Subject: [PATCH 04/30] sharding: get_eligible_collator with tests Former-commit-id: 19bcd3b213dec79c4fa634e31105c7e09cd7ffd2 [formerly be97e08143820904c399eff1f9b27dccc84bf3c0] Former-commit-id: e1c18d06271f0df5c667823372ff8f314a6d9f82 --- sharding/contracts/sharding_manager.sol | 40 +++++---- sharding/contracts/sharding_manager_test.go | 91 ++++++++++++++++----- 2 files changed, 93 insertions(+), 38 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index f6a8d0354..b5aeb7a27 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -87,10 +87,10 @@ contract SMC { uint constant PROPOSER_DEPOSIT = 1 ether; // The minimum balance of a proposer (for collators) uint constant MIN_PROPOSER_BALANCE = 0.1 ether; - // Time the ether is locked by collators - uint constant COLLATOR_LOCKUP_LENGTH = 16128; - // Time the ether is locked by proposers - uint constant PROPOSER_LOCKUP_LENGTH = 48; + // Time the ether is locked by collators (Not constant for testing) + uint COLLATOR_LOCKUP_LENGTH = 16128; + // Time the ether is locked by proposers (Not constant for testing) + uint PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract // is able to return the collator of that period uint constant LOOKAHEAD_LENGTH = 4; @@ -98,25 +98,31 @@ contract SMC { // Log the latest period number of the shard mapping (int => int) public period_head; - function SMC() public { + function SMC(uint collator_lockup_length, uint proposer_lockup_length) public { + COLLATOR_LOCKUP_LENGTH = collator_lockup_length; + PROPOSER_LOCKUP_LENGTH = proposer_lockup_length; } + event LOG(uint L); // Uses a block hash as a seed to pseudorandomly select a signer from the collator pool. // [TODO] Chance of being selected should be proportional to the collator's deposit. // Should be able to return a value for the current period or any future period up to. - function get_eligible_collator(uint256 shard_id, uint256 period) public view returns(address) { - require(period >= LOOKAHEAD_LENGTH); - require((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH < block.number); + function get_eligible_collator(uint shard_id, uint period) public view returns(address) { + uint current_period = block.number / PERIOD_LENGTH; + uint period_to_look = ((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH); + require(period >= current_period); + require(period <= (current_period + LOOKAHEAD_LENGTH)); require(collator_pool_len > 0); - // [TODO] Should check further if this safe or not - return collator_pool[ - uint( - keccak256( - uint(block.blockhash((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH)), - shard_id - ) - ) % - collator_pool_len + if (period <= LOOKAHEAD_LENGTH) + period_to_look = period; + require(period_to_look < block.number); + return collator_pool[uint( + keccak256( + block.blockhash(period_to_look), + shard_id + ) + ) % + collator_pool_len ]; } diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 6f3c4d903..9b5941f01 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -1,6 +1,7 @@ package contracts import ( + "crypto/ecdsa" "math/big" "testing" @@ -12,23 +13,32 @@ import ( "github.com/ethereum/go-ethereum/crypto" ) +type SMCConfig struct { + collatorLockupLenght *big.Int + proposerLockupLength *big.Int +} + var ( - key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - addr = crypto.PubkeyToAddress(key.PublicKey) + mainKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") accountBalance1001Eth, _ = new(big.Int).SetString("1001000000000000000000", 10) collatorDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) + smcConfig = SMCConfig{ + collatorLockupLenght: new(big.Int).SetInt64(1), + proposerLockupLength: new(big.Int).SetInt64(1), + } ) -func deploySMCContract(backend *backends.SimulatedBackend) (common.Address, *types.Transaction, *SMC, error) { +func deploySMCContract(backend *backends.SimulatedBackend, key *ecdsa.PrivateKey) (common.Address, *types.Transaction, *SMC, error) { transactOpts := bind.NewKeyedTransactor(key) defer backend.Commit() - return DeploySMC(transactOpts, backend) + return DeploySMC(transactOpts, backend, smcConfig.collatorLockupLenght, smcConfig.proposerLockupLength) } // Test creating the SMC contract func TestContractCreation(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - _, _, _, err := deploySMCContract(backend) + _, _, _, err := deploySMCContract(backend, mainKey) backend.Commit() if err != nil { t.Fatalf("can't deploy SMC: %v", err) @@ -37,12 +47,13 @@ func TestContractCreation(t *testing.T) { // Test register collator func TestCollatorDeposit(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - transactOpts := bind.NewKeyedTransactor(key) - _, _, smc, _ := deploySMCContract(backend) + transactOpts := bind.NewKeyedTransactor(mainKey) + _, _, smc, _ := deploySMCContract(backend, mainKey) // Test register_collator() function - // Deposit 100 Eth + // Deposit 1000 Eth transactOpts.Value = collatorDeposit if _, err := smc.Register_collator(transactOpts); err != nil { @@ -84,11 +95,12 @@ func TestCollatorDeposit(t *testing.T) { } } -// Test collator withdraw from the pool -func TestCollatorWithdraw(t *testing.T) { +// Test collator deregister from pool +func TestCollatorDeregister(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - transactOpts := bind.NewKeyedTransactor(key) - _, _, smc, _ := deploySMCContract(backend) + transactOpts := bind.NewKeyedTransactor(mainKey) + _, _, smc, _ := deploySMCContract(backend, mainKey) transactOpts.Value = collatorDeposit // Register collator @@ -113,13 +125,50 @@ func TestCollatorWithdraw(t *testing.T) { if withdrawsEventsIterator.Event.Pool_index.Cmp(big.NewInt(0)) != 0 { t.Fatalf("Collator index mismatch: %d should be 0", withdrawsEventsIterator.Event.Pool_index) } - // for i := 0; i < 16128*5+1; i++ { - // backend.Commit() - // } - - // Release collator - // _, err = smc.Release_collator(transactOpts) - // if err != nil { - // t.Fatalf("Failed to release collator: %v", err) - // } +} + +func TestGetEligibleCollator(t *testing.T) { + const numberCollators = 20 + var collatorPoolAddr [numberCollators]common.Address + var collatorPoolPrivKeys [numberCollators]*ecdsa.PrivateKey + var transactOpts [numberCollators]*bind.TransactOpts + genesis := make(core.GenesisAlloc) + + for i := 0; i < numberCollators; i++ { + key, _ := crypto.GenerateKey() + collatorPoolPrivKeys[i] = key + collatorPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) + transactOpts[i] = bind.NewKeyedTransactor(key) + transactOpts[i].Value = collatorDeposit + + genesis[collatorPoolAddr[i]] = core.GenesisAccount{ + Balance: accountBalance1001Eth, + } + } + + backend := backends.NewSimulatedBackend(genesis) + _, _, smc, _ := deploySMCContract(backend, collatorPoolPrivKeys[0]) + + // Register collator + for i := 0; i < numberCollators; i++ { + smc.Register_collator(transactOpts[i]) + } + + // Move blockchain 4 blocks further (Head is at 5 after) : period 1 + for i := 0; i < 4; i++ { + backend.Commit() + } + + _, err := smc.Get_eligible_collator(&bind.CallOpts{}, big.NewInt(0), big.NewInt(4)) + if err != nil { + t.Fatalf("Cannot get eligible collator: %v", err) + } + // after: Head is 11, period 2 + for i := 0; i < 6; i++ { + backend.Commit() + } + _, err = smc.Get_eligible_collator(&bind.CallOpts{}, big.NewInt(1), big.NewInt(6)) + if err != nil { + t.Fatalf("Cannot get eligible collator: %v\n", err) + } } From ddc67976feb914e51bb5185d59316f3d482d1483 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Wed, 18 Apr 2018 10:55:59 -0700 Subject: [PATCH 05/30] sharding: /collator/noatry and align constants w/ phase 1.1 spec Former-commit-id: eefbc5f230aea78eb30adc8bb09f7ce7a5844043 [formerly dc9a760f78d3a4d356e9f9d6ccf8b39129ce756f] Former-commit-id: cff011989f46e2235e700bd84278043038014367 --- sharding/contracts/sharding_manager.sol | 124 ++++++++++++------------ 1 file changed, 63 insertions(+), 61 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index b5aeb7a27..086db5ee0 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -5,20 +5,20 @@ contract SMC { bytes32 chunk_root, int128 period, int128 height, address proposer_address, uint proposer_bid, bytes proposer_signature); - event CollatorRegistered(address collator, uint pool_index); - event CollatorDeregistered(uint pool_index); - event CollatorReleased(uint pool_index); + event NotaryRegistered(address notary, uint pool_index); + event NotaryDeregistered(address notary, uint pool_index, int128 deregistered_period); + event NotaryReleased(address notary, uint pool_index); event ProposerRegistered(uint pool_index); event ProposerDeregistered(uint index); event ProposerReleased(uint index); - // Entry in collator_registry - struct Collator { - // When collator asked for unregistration + // Entry in notary_registry + struct Notary { + // When notary asked for unregistration uint deregistered; - // The collator's pool index + // The notary's pool index uint pool_index; - // False if collator has not deposited, true otherwise + // False if notary has not deposited, true otherwise bool deposited; } @@ -45,19 +45,19 @@ contract SMC { struct HeaderVars { bytes32 entireHeaderHash; int score; - address collatorAddr; + address notaryAddr; bool isNewHead; } - // collatorId => Collators - // mapping (int => Collator) public collators; - address[] public collator_pool; + // notaryId => Notaries + // mapping (int => Notary) public notaries; + address[] public notary_pool; // proposerId => Proposer // mapping (int => Proposer) public proposers; Proposer[] public proposer_pool; - // Collator registry (deregistered is 0 for not yet deregistered collators) - mapping (address => Collator) public collator_registry; + // Notary registry (deregistered is 0 for not yet deregistered notaries) + mapping (address => Notary) public notary_registry; mapping (address => Proposer) public proposer_registry; // shard_id => (header_hash => tree root) mapping (uint => mapping (bytes32 => bytes32)) public collation_trees; @@ -66,8 +66,8 @@ contract SMC { // shardId => headerHash mapping (int => bytes32) shardead; - // Number of collators - uint public collator_pool_len; + // Number of notaries + uint public notary_pool_len; // Indexes of empty slots caused by the function `withdraw` uint[] empty_slots_stack; // The top index of the stack in empty_slots_stack @@ -77,52 +77,54 @@ contract SMC { uint constant PERIOD_LENGTH = 5; // Exact collation body size (1mb) uint constant COLLATION_SIZE = 2 ** 20; - // Subsidy in vEth - uint constant COLLATOR_SUBSIDY = 0.001 ether; // Number of shards uint constant SHARD_COUNT = 100; - // The minimum deposit size for a collator - uint constant COLLATOR_DEPOSIT = 1000 ether; + // The minimum deposit size for a notary + uint constant NOTARY_DEPOSIT = 1000 ether; // The minimum deposit size for a proposer uint constant PROPOSER_DEPOSIT = 1 ether; - // The minimum balance of a proposer (for collators) + // The minimum balance of a proposer (for notaries) uint constant MIN_PROPOSER_BALANCE = 0.1 ether; - // Time the ether is locked by collators (Not constant for testing) - uint COLLATOR_LOCKUP_LENGTH = 16128; + // Time the ether is locked by notaries (Not constant for testing) + uint constant NOTARY_LOCKUP_LENGTH = 16128; // Time the ether is locked by proposers (Not constant for testing) uint PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract - // is able to return the collator of that period + // is able to return the notary of that period uint constant LOOKAHEAD_LENGTH = 4; + // Number of notaries to select from notary pool for each shard in each period + uint constant COMMITTEE_SIZE = 135; + // Threshold(number of notaries in committee) for a proposal to be deem accepted + uint constant QUORUM_SIZE = 90; // Log the latest period number of the shard mapping (int => int) public period_head; - function SMC(uint collator_lockup_length, uint proposer_lockup_length) public { - COLLATOR_LOCKUP_LENGTH = collator_lockup_length; + function SMC(uint notary_lockup_length, uint proposer_lockup_length) public { + COLLATOR_LOCKUP_LENGTH = notary_lockup_length; PROPOSER_LOCKUP_LENGTH = proposer_lockup_length; } event LOG(uint L); - // Uses a block hash as a seed to pseudorandomly select a signer from the collator pool. - // [TODO] Chance of being selected should be proportional to the collator's deposit. + // Uses a block hash as a seed to pseudorandomly select a signer from the notary pool. + // [TODO] Chance of being selected should be proportional to the notary's deposit. // Should be able to return a value for the current period or any future period up to. - function get_eligible_collator(uint shard_id, uint period) public view returns(address) { + function get_eligible_notary(uint shard_id, uint period) public view returns(address) { uint current_period = block.number / PERIOD_LENGTH; uint period_to_look = ((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH); require(period >= current_period); require(period <= (current_period + LOOKAHEAD_LENGTH)); - require(collator_pool_len > 0); + require(notary_pool_len > 0); if (period <= LOOKAHEAD_LENGTH) period_to_look = period; require(period_to_look < block.number); - return collator_pool[uint( + return notary_pool[uint( keccak256( block.blockhash(period_to_look), shard_id ) ) % - collator_pool_len + notary_pool_len ]; } @@ -135,57 +137,57 @@ contract SMC { } - function register_collator() public payable returns(bool) { - address collator_address = msg.sender; - require(!collator_registry[collator_address].deposited); + function register_notary() public payable returns(bool) { + address notary_address = msg.sender; + require(!notary_registry[notary_address].deposited); require(msg.value == COLLATOR_DEPOSIT); uint index; if (!empty_stack()) { index = stack_pop(); - collator_pool[index] = collator_address; + notary_pool[index] = notary_address; } else { - index = collator_pool_len; - collator_pool.push(collator_address); + index = notary_pool_len; + notary_pool.push(notary_address); } - ++collator_pool_len; + ++notary_pool_len; - collator_registry[collator_address] = Collator({ + notary_registry[notary_address] = Notary({ deregistered: 0, pool_index: index, deposited: true }); - CollatorRegistered(collator_address, index); + NotaryRegistered(notary_address, index); return true; } - // Removes the collator from the collator pool and sets deregistered period - function deregister_collator() public { - address collator_address = msg.sender; - uint index = collator_registry[collator_address].pool_index; - // Check if collator deposited - require(collator_registry[collator_address].deposited); - require(collator_pool[index] == collator_address); + // Removes the notary from the notary pool and sets deregistered period + function deregister_notary() public { + address notary_address = msg.sender; + uint index = notary_registry[notary_address].pool_index; + // Check if notary deposited + require(notary_registry[notary_address].deposited); + require(notary_pool[index] == notary_address); // Deregistered period - collator_registry[collator_address].deregistered = block.number / PERIOD_LENGTH; + notary_registry[notary_address].deregistered = block.number / PERIOD_LENGTH; stack_push(index); - --collator_pool_len; - CollatorDeregistered(index); + --notary_pool_len; + NotaryDeregistered(index); } - function release_collator() public { - address collator_address = msg.sender; - require(collator_registry[collator_address].deposited == true); + function release_notary() public { + address notary_address = msg.sender; + require(notary_registry[notary_address].deposited == true); // Deregistered - require(collator_registry[collator_address].deregistered != 0); + require(notary_registry[notary_address].deregistered != 0); // Locked up period - require((block.number / PERIOD_LENGTH) > (collator_registry[collator_address].deregistered + COLLATOR_LOCKUP_LENGTH)); + require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered + COLLATOR_LOCKUP_LENGTH)); - delete collator_registry[collator_address]; - collator_address.transfer(COLLATOR_DEPOSIT); + delete notary_registry[notary_address]; + notary_address.transfer(COLLATOR_DEPOSIT); } function register_proposer() public payable returns(int) { @@ -235,9 +237,9 @@ contract SMC { // assert(periodHead[_shardId] < int(_expectedPeriodNumber)); // // Check the signature with validation_code_addr - // headerVars.collatorAddr = getEligibleCollator(_shardId, block.number/periodLength); - // require(headerVars.collatorAddr != 0x0); - // require(msg.sender == headerVars.collatorAddr); + // headerVars.notaryAddr = getEligibleNotary(_shardId, block.number/periodLength); + // require(headerVars.notaryAddr != 0x0); + // require(msg.sender == headerVars.notaryAddr); // // Check score == collationNumber // headerVars.score = collationHeaders[_shardId][_parentHash].score + 1; From 4bfa96219fb24c7f22f169f1520e4b9cd35848fa Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Wed, 18 Apr 2018 11:26:09 -0700 Subject: [PATCH 06/30] sharding: fixed up on notary's register, deregister, release functions Former-commit-id: c59f4274aa31f240a8b41f86d36de38782b1998b [formerly f7bc669d44adb550e2902d8ff8f210eb30630aed] Former-commit-id: 8214f75adeef0c8316bd2fbdee648548a96b91ad --- sharding/contracts/sharding_manager.sol | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 086db5ee0..c95333e84 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -6,7 +6,7 @@ contract SMC { address proposer_address, uint proposer_bid, bytes proposer_signature); event NotaryRegistered(address notary, uint pool_index); - event NotaryDeregistered(address notary, uint pool_index, int128 deregistered_period); + event NotaryDeregistered(address notary, uint pool_index, uint deregistered_period); event NotaryReleased(address notary, uint pool_index); event ProposerRegistered(uint pool_index); event ProposerDeregistered(uint index); @@ -86,7 +86,7 @@ contract SMC { // The minimum balance of a proposer (for notaries) uint constant MIN_PROPOSER_BALANCE = 0.1 ether; // Time the ether is locked by notaries (Not constant for testing) - uint constant NOTARY_LOCKUP_LENGTH = 16128; + uint NOTARY_LOCKUP_LENGTH = 16128; // Time the ether is locked by proposers (Not constant for testing) uint PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract @@ -101,7 +101,7 @@ contract SMC { mapping (int => int) public period_head; function SMC(uint notary_lockup_length, uint proposer_lockup_length) public { - COLLATOR_LOCKUP_LENGTH = notary_lockup_length; + NOTARY_LOCKUP_LENGTH = notary_lockup_length; PROPOSER_LOCKUP_LENGTH = proposer_lockup_length; } @@ -140,7 +140,7 @@ contract SMC { function register_notary() public payable returns(bool) { address notary_address = msg.sender; require(!notary_registry[notary_address].deposited); - require(msg.value == COLLATOR_DEPOSIT); + require(msg.value == NOTARY_DEPOSIT); uint index; if (!empty_stack()) { @@ -163,7 +163,7 @@ contract SMC { } // Removes the notary from the notary pool and sets deregistered period - function deregister_notary() public { + function deregister_notary() public returns(bool) { address notary_address = msg.sender; uint index = notary_registry[notary_address].pool_index; // Check if notary deposited @@ -171,23 +171,28 @@ contract SMC { require(notary_pool[index] == notary_address); // Deregistered period - notary_registry[notary_address].deregistered = block.number / PERIOD_LENGTH; + uint deregistered_period = block.number / PERIOD_LENGTH; + notary_registry[notary_address].deregistered = deregistered_period; stack_push(index); --notary_pool_len; - NotaryDeregistered(index); + NotaryDeregistered(notary_address, index, deregistered_period); + return true; } - function release_notary() public { + function release_notary() public returns(bool) { address notary_address = msg.sender; + uint index = notary_registry[notary_address].pool_index; require(notary_registry[notary_address].deposited == true); // Deregistered require(notary_registry[notary_address].deregistered != 0); // Locked up period - require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered + COLLATOR_LOCKUP_LENGTH)); + require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered + NOTARY_LOCKUP_LENGTH)); delete notary_registry[notary_address]; - notary_address.transfer(COLLATOR_DEPOSIT); + notary_address.transfer(NOTARY_DEPOSIT); + NotaryReleased(notary_address, index); + return true; } function register_proposer() public payable returns(int) { From ce9a72455609c96265c5d4c97fd61941339e7681 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Wed, 18 Apr 2018 13:51:31 -0700 Subject: [PATCH 07/30] sharding: monitoring notary size at current period and make adjustment next period Former-commit-id: 3a40788c3dad272570980e426c751a9431908a0a [formerly 6149e9eae68a5e7e6f6b87adeafa6467582caeeb] Former-commit-id: 175c0d263e3a5486cc583640f819c8c1d77adff0 --- sharding/contracts/sharding_manager.sol | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index c95333e84..a728552e4 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -73,6 +73,11 @@ contract SMC { // The top index of the stack in empty_slots_stack uint empty_slots_stack_top; + // Notary sampling info to keep sample size unchaged through out period + uint current_period_notary_sample_size; + uint next_period_notary_sample_size; + uint sample_size_last_updated_period; + // Constant values uint constant PERIOD_LENGTH = 5; // Exact collation body size (1mb) @@ -81,6 +86,8 @@ contract SMC { uint constant SHARD_COUNT = 100; // The minimum deposit size for a notary uint constant NOTARY_DEPOSIT = 1000 ether; + // The reward for notary on voting for a collation + uint constant NOTARY_REWARD = 0.001 ether; // The minimum deposit size for a proposer uint constant PROPOSER_DEPOSIT = 1 ether; // The minimum balance of a proposer (for notaries) @@ -141,6 +148,9 @@ contract SMC { address notary_address = msg.sender; require(!notary_registry[notary_address].deposited); require(msg.value == NOTARY_DEPOSIT); + + // update notary_sample_size + update_notary_sample_size(); uint index; if (!empty_stack()) { @@ -158,6 +168,12 @@ contract SMC { pool_index: index, deposited: true }); + + // if current index is greater than notary_sample_size, increase notary_sample_size for next period + if (index >= next_period_notary_sample_size) { + next_period_notary_sample_size = index + 1; + } + NotaryRegistered(notary_address, index); return true; } @@ -169,6 +185,9 @@ contract SMC { // Check if notary deposited require(notary_registry[notary_address].deposited); require(notary_pool[index] == notary_address); + + // update notary_sample_size + update_notary_sample_size(); // Deregistered period uint deregistered_period = block.number / PERIOD_LENGTH; @@ -195,6 +214,15 @@ contract SMC { return true; } + function update_notary_sample_size() returns(bool) { + uint current_period = block.number / PERIOD_LENGTH; + require(current_period < sample_size_last_updated_period); + + current_period_notary_sample_size = next_period_notary_sample_size; + sample_size_last_updated_period = current_period; + return true; + } + function register_proposer() public payable returns(int) { } From 7107f8fa2ba4ed91715ccfcfaaefc9cc6edfe4ef Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Wed, 18 Apr 2018 17:46:41 -0700 Subject: [PATCH 08/30] sharding: function to check notary in committee Former-commit-id: d46016ebd3bacbb50cbc03084054ce21c9ac9d81 [formerly 6a95cdcdc60bb4dc6a359735f618ed765553095a] Former-commit-id: 3db9a81c0d2995ff474b3c10b3b87f8f3432a495 --- sharding/contracts/sharding_manager.sol | 39 +++++++++++++------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index a728552e4..7747e1c8c 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -73,7 +73,7 @@ contract SMC { // The top index of the stack in empty_slots_stack uint empty_slots_stack_top; - // Notary sampling info to keep sample size unchaged through out period + // Notary sample size at current period and next period uint current_period_notary_sample_size; uint next_period_notary_sample_size; uint sample_size_last_updated_period; @@ -116,23 +116,26 @@ contract SMC { // Uses a block hash as a seed to pseudorandomly select a signer from the notary pool. // [TODO] Chance of being selected should be proportional to the notary's deposit. // Should be able to return a value for the current period or any future period up to. - function get_eligible_notary(uint shard_id, uint period) public view returns(address) { + function is_notary_in_committee(uint shard_id, uint period) public view returns(bool) { uint current_period = block.number / PERIOD_LENGTH; - uint period_to_look = ((period - LOOKAHEAD_LENGTH) * PERIOD_LENGTH); - require(period >= current_period); - require(period <= (current_period + LOOKAHEAD_LENGTH)); - require(notary_pool_len > 0); - if (period <= LOOKAHEAD_LENGTH) - period_to_look = period; - require(period_to_look < block.number); - return notary_pool[uint( - keccak256( - block.blockhash(period_to_look), - shard_id - ) - ) % - notary_pool_len - ]; + + // Determine notary pool length based on notary sample size + uint sample_size; + if (period > sample_size_last_updated_period) { + sample_size = next_period_notary_sample_size; + } else { + sample_size = current_period_notary_sample_size; + } + + uint period_to_look = period * PERIOD_LENGTH - 1; + + for (uint i = 1; i <= QUORUM_SIZE; i++) { + uint index = uint(keccak256(block.blockhash(period_to_look), index)) % sample_size; + if (notary_pool[index] == msg.sender) { + return true; + } + } + return false; } function compute_header_hash(uint256 shard_id, @@ -214,7 +217,7 @@ contract SMC { return true; } - function update_notary_sample_size() returns(bool) { + function update_notary_sample_size() private returns(bool) { uint current_period = block.number / PERIOD_LENGTH; require(current_period < sample_size_last_updated_period); From b5e77c3867a1893119d842be2e462d4267652be4 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 19 Apr 2018 10:39:58 -0700 Subject: [PATCH 09/30] sharding: cleaned up comments in code Former-commit-id: e733ef576dfa5ab1165bea1bf2c1502c01de0ebd [formerly 9694cff89a1bc823e3f069f40564947715475c11] Former-commit-id: 3a7109e6f02ec648390f2f6364e71ebb288b5bd9 --- sharding/contracts/sharding_manager.sol | 106 +++++------------------- 1 file changed, 19 insertions(+), 87 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 7747e1c8c..bbed1affa 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -12,33 +12,26 @@ contract SMC { event ProposerDeregistered(uint index); event ProposerReleased(uint index); - // Entry in notary_registry struct Notary { - // When notary asked for unregistration - uint deregistered; - // The notary's pool index + uint deregistered_period; uint pool_index; - // False if notary has not deposited, true otherwise bool deposited; } - // Entry in proposer_registry struct Proposer { - // Shard id of the deposit - uint shardId; - // Deposit in ether in each shard - uint[] deposit; + uint deregistered_period; + uint balances } struct CollationHeader { - uint256 shard_id; // pointer to shard - bytes32 parent_hash; // pointer to parent header - bytes32 chunk_root; // pointer to collation body - int128 period; // Period which header should be included - int128 height; // Collation's height - address proposer_address; // Proposer's address - uint256 proposer_bid; // Proposer's bid - bytes proposer_signature; // Proposer's signature + uint shard_id; // Number of the shard ID + bytes32 parent_hash; // Hash of the parent collation + bytes32 chunk_root; // Root hash of the collation body + uint period; // Period which header should be included + uint height; // Height of the collation + address proposer_address; + uint proposer_bid; + bytes proposer_signature; } // Packed variables to be used in addHeader @@ -49,11 +42,7 @@ contract SMC { bool isNewHead; } - // notaryId => Notaries - // mapping (int => Notary) public notaries; address[] public notary_pool; - // proposerId => Proposer - // mapping (int => Proposer) public proposers; Proposer[] public proposer_pool; // Notary registry (deregistered is 0 for not yet deregistered notaries) @@ -113,9 +102,8 @@ contract SMC { } event LOG(uint L); - // Uses a block hash as a seed to pseudorandomly select a signer from the notary pool. - // [TODO] Chance of being selected should be proportional to the notary's deposit. - // Should be able to return a value for the current period or any future period up to. + + function is_notary_in_committee(uint shard_id, uint period) public view returns(bool) { uint current_period = block.number / PERIOD_LENGTH; @@ -152,7 +140,6 @@ contract SMC { require(!notary_registry[notary_address].deposited); require(msg.value == NOTARY_DEPOSIT); - // update notary_sample_size update_notary_sample_size(); uint index; @@ -167,7 +154,7 @@ contract SMC { ++notary_pool_len; notary_registry[notary_address] = Notary({ - deregistered: 0, + deregistered_period: 0, pool_index: index, deposited: true }); @@ -181,20 +168,16 @@ contract SMC { return true; } - // Removes the notary from the notary pool and sets deregistered period function deregister_notary() public returns(bool) { address notary_address = msg.sender; uint index = notary_registry[notary_address].pool_index; - // Check if notary deposited require(notary_registry[notary_address].deposited); require(notary_pool[index] == notary_address); - // update notary_sample_size update_notary_sample_size(); - // Deregistered period uint deregistered_period = block.number / PERIOD_LENGTH; - notary_registry[notary_address].deregistered = deregistered_period; + notary_registry[notary_address].deregistered_period = deregistered_period; stack_push(index); --notary_pool_len; @@ -206,10 +189,8 @@ contract SMC { address notary_address = msg.sender; uint index = notary_registry[notary_address].pool_index; require(notary_registry[notary_address].deposited == true); - // Deregistered - require(notary_registry[notary_address].deregistered != 0); - // Locked up period - require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered + NOTARY_LOCKUP_LENGTH)); + require(notary_registry[notary_address].deregistered_period != 0); + require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered_period + NOTARY_LOCKUP_LENGTH)); delete notary_registry[notary_address]; notary_address.transfer(NOTARY_DEPOSIT); @@ -246,61 +227,12 @@ contract SMC { } - // Attempts to process a collation header, returns true on success, reverts on failure. function addHeader(uint _shardId, uint period, bytes32 height, bytes32 _parent_hash, bytes32 chunk_root, address proposer_address, uint proposer_bid, bytes proposer_signature) public returns(bool) { - // HeaderVars memory headerVars; - - // // Check if the header is valid - // require((_shardId >= 0) && (_shardId < shardCount)); - // require(block.number >= periodLength); - // require(_expectedPeriodNumber == block.number / periodLength); - // require(_periodStartPrevHash == block.blockhash(_expectedPeriodNumber * periodLength - 1)); - - // // Check if this header already exists - // headerVars.entireHeaderHash = keccak256(_shardId, _expectedPeriodNumber, _periodStartPrevHash, - // _parentHash, _transactionRoot, bytes32(_coinbase), - // _stateRoot, _receiptRoot, _number); - // assert(collationHeaders[_shardId][headerVars.entireHeaderHash].score == 0); - // // Check whether the parent exists. - // // if (parent_collation_hash == 0), i.e., is the genesis, - // // then there is no need to check. - // if (_parentHash != 0x0) - // assert(collationHeaders[_shardId][_parentHash].score > 0); - // // Check if only one collation in one period - // assert(periodHead[_shardId] < int(_expectedPeriodNumber)); - - // // Check the signature with validation_code_addr - // headerVars.notaryAddr = getEligibleNotary(_shardId, block.number/periodLength); - // require(headerVars.notaryAddr != 0x0); - // require(msg.sender == headerVars.notaryAddr); - - // // Check score == collationNumber - // headerVars.score = collationHeaders[_shardId][_parentHash].score + 1; - // require(_number == headerVars.score); - - // // Add the header - // collationHeaders[_shardId][headerVars.entireHeaderHash] = CollationHeader({ - // parentHash: _parentHash, - // score: headerVars.score - // }); - - // // Update the latest period number - // periodHead[_shardId] = int(_expectedPeriodNumber); - - // // Determine the head - // if (headerVars.score > collationHeaders[_shardId][shardHead[_shardId]].score) { - // shardHead[_shardId] = headerVars.entireHeaderHash; - // headerVars.isNewHead = true; - // } - - // CollationAdded(_shardId, _expectedPeriodNumber, _periodStartPrevHash, - // _parentHash, _transactionRoot, _coinbase, _stateRoot, - // _receiptRoot, _number, headerVars.isNewHead, headerVars.score); - - // return true; + // TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, + // all others don’t. This function just emits a log } From 5e2b6274a7cdc196e3f477fbd13701abe253681f Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 19 Apr 2018 11:32:26 -0700 Subject: [PATCH 10/30] sharding: fixed naming styles Former-commit-id: 4e50f1f8edc38d24b265e540c060a4c0bbf52052 [formerly df906e85f5ab5fb27afce1569a4f2992a7169527] Former-commit-id: 5fd3454d63cd3fb05288a413bb78d887eeac08c9 --- sharding/contracts/sharding_manager.sol | 216 ++++++++++++------------ 1 file changed, 109 insertions(+), 107 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index bbed1affa..241eb06b3 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -13,25 +13,25 @@ contract SMC { event ProposerReleased(uint index); struct Notary { - uint deregistered_period; - uint pool_index; + uint deregisteredPeriod; + uint poolIndex; bool deposited; } struct Proposer { - uint deregistered_period; + uint deregisteredPeriod; uint balances } struct CollationHeader { - uint shard_id; // Number of the shard ID - bytes32 parent_hash; // Hash of the parent collation - bytes32 chunk_root; // Root hash of the collation body + uint shardId; // Number of the shard ID + bytes32 parentHash; // Hash of the parent collation + bytes32 chunkRoot; // Root hash of the collation body uint period; // Period which header should be included uint height; // Height of the collation - address proposer_address; - uint proposer_bid; - bytes proposer_signature; + address proposerAddress; + uint proposerBid; + bytes proposerSignature; } // Packed variables to be used in addHeader @@ -42,30 +42,30 @@ contract SMC { bool isNewHead; } - address[] public notary_pool; - Proposer[] public proposer_pool; + address[] public notaryPool; + Proposer[] public proposerPool; // Notary registry (deregistered is 0 for not yet deregistered notaries) - mapping (address => Notary) public notary_registry; - mapping (address => Proposer) public proposer_registry; - // shard_id => (header_hash => tree root) - mapping (uint => mapping (bytes32 => bytes32)) public collation_trees; + mapping (address => Notary) public notaryRegistry; + mapping (address => Proposer) public proposerRegistry; + // shardId => (header_hash => tree root) + mapping (uint => mapping (bytes32 => bytes32)) public collationTrees; // shardId => (headerHash => CollationHeader) mapping (int => mapping (bytes32 => CollationHeader)) public collationHeaders; // shardId => headerHash mapping (int => bytes32) shardead; // Number of notaries - uint public notary_pool_len; + uint public notaryPoolLength; // Indexes of empty slots caused by the function `withdraw` - uint[] empty_slots_stack; - // The top index of the stack in empty_slots_stack - uint empty_slots_stack_top; + uint[] emptySlotsStack; + // The top index of the stack in emptySlotsStack + uint emptySlotsStackTop; // Notary sample size at current period and next period - uint current_period_notary_sample_size; - uint next_period_notary_sample_size; - uint sample_size_last_updated_period; + uint currentPeriodNotarySampleSize; + uint nextPeriodNotarySampleSize; + uint sampleSizeLastUpdatedPeriod; // Constant values uint constant PERIOD_LENGTH = 5; @@ -79,11 +79,11 @@ contract SMC { uint constant NOTARY_REWARD = 0.001 ether; // The minimum deposit size for a proposer uint constant PROPOSER_DEPOSIT = 1 ether; - // The minimum balance of a proposer (for notaries) + // The minimum balance of a proposer uint constant MIN_PROPOSER_BALANCE = 0.1 ether; - // Time the ether is locked by notaries (Not constant for testing) + // Time the ether is locked by notaries uint NOTARY_LOCKUP_LENGTH = 16128; - // Time the ether is locked by proposers (Not constant for testing) + // Time the ether is locked by proposers uint PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract // is able to return the notary of that period @@ -94,7 +94,7 @@ contract SMC { uint constant QUORUM_SIZE = 90; // Log the latest period number of the shard - mapping (int => int) public period_head; + mapping (int => int) public periodHead; function SMC(uint notary_lockup_length, uint proposer_lockup_length) public { NOTARY_LOCKUP_LENGTH = notary_lockup_length; @@ -104,155 +104,157 @@ contract SMC { event LOG(uint L); - function is_notary_in_committee(uint shard_id, uint period) public view returns(bool) { - uint current_period = block.number / PERIOD_LENGTH; + function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { + uint currentPeriod = block.number / PERIOD_LENGTH; // Determine notary pool length based on notary sample size - uint sample_size; - if (period > sample_size_last_updated_period) { - sample_size = next_period_notary_sample_size; + uint sampleSize; + if (period > sampleSizeLastUpdatedPeriod) { + sampleSize = nextPeriodNotarySampleSize; } else { - sample_size = current_period_notary_sample_size; + sampleSize = currentPeriodNotarySampleSize; } - uint period_to_look = period * PERIOD_LENGTH - 1; + uint periodToLook = period * PERIOD_LENGTH - 1; for (uint i = 1; i <= QUORUM_SIZE; i++) { - uint index = uint(keccak256(block.blockhash(period_to_look), index)) % sample_size; - if (notary_pool[index] == msg.sender) { + uint index = uint(keccak256(block.blockhash(periodToLook), index)) % sampleSize; + if (notaryPool[index] == msg.sender) { return true; } } return false; } - function compute_header_hash(uint256 shard_id, - bytes32 parent_hash, - bytes32 chunk_root, - uint256 period, - address proposer_address, - uint256 proposer_bid) public returns(bytes32){ - - } - - function register_notary() public payable returns(bool) { - address notary_address = msg.sender; - require(!notary_registry[notary_address].deposited); + function registerNotary() public payable returns(bool) { + address notaryAddress = msg.sender; + require(!notaryRegistry[notaryAddress].deposited); require(msg.value == NOTARY_DEPOSIT); - update_notary_sample_size(); + updateNotarySampleSize(); uint index; - if (!empty_stack()) { - index = stack_pop(); - notary_pool[index] = notary_address; + if (!emptyStack()) { + index = stackPop(); + notaryPool[index] = notaryAddress; } else { - index = notary_pool_len; - notary_pool.push(notary_address); + index = notaryPoolLength; + notaryPool.push(notaryAddress); } - ++notary_pool_len; + ++notaryPoolLength; - notary_registry[notary_address] = Notary({ - deregistered_period: 0, - pool_index: index, + notaryRegistry[notaryAddress] = Notary({ + deregisteredPeriod: 0, + poolIndex: index, deposited: true }); - // if current index is greater than notary_sample_size, increase notary_sample_size for next period - if (index >= next_period_notary_sample_size) { - next_period_notary_sample_size = index + 1; + // if current index is greater than notary sample size, increase notary sample size for next period + if (index >= nextPeriodNotarySampleSize) { + nextPeriodNotarySampleSize = index + 1; } - NotaryRegistered(notary_address, index); + NotaryRegistered(notaryAddress, index); return true; } - function deregister_notary() public returns(bool) { - address notary_address = msg.sender; - uint index = notary_registry[notary_address].pool_index; - require(notary_registry[notary_address].deposited); - require(notary_pool[index] == notary_address); + function deregisterNotary() public returns(bool) { + address notaryAddress = msg.sender; + uint index = notaryRegistry[notaryAddress].poolIndex; + require(notaryRegistry[notaryAddress].deposited); + require(notaryPool[index] == notaryAddress); - update_notary_sample_size(); + updateNotarySampleSize(); - uint deregistered_period = block.number / PERIOD_LENGTH; - notary_registry[notary_address].deregistered_period = deregistered_period; + uint deregisteredPeriod = block.number / PERIOD_LENGTH; + notaryRegistry[notaryAddress].deregisteredPeriod = deregisteredPeriod; - stack_push(index); - --notary_pool_len; - NotaryDeregistered(notary_address, index, deregistered_period); + stackPush(index); + --notaryPoolLength; + NotaryDeregistered(notaryAddress, index, deregisteredPeriod); return true; } - function release_notary() public returns(bool) { - address notary_address = msg.sender; - uint index = notary_registry[notary_address].pool_index; - require(notary_registry[notary_address].deposited == true); - require(notary_registry[notary_address].deregistered_period != 0); - require((block.number / PERIOD_LENGTH) > (notary_registry[notary_address].deregistered_period + NOTARY_LOCKUP_LENGTH)); + function releaseNotary() public returns(bool) { + address notaryAddress = msg.sender; + uint index = notaryRegistry[notaryAddress].poolIndex; + require(notaryRegistry[notaryAddress].deposited == true); + require(notaryRegistry[notaryAddress].deregisteredPeriod != 0); + require((block.number / PERIOD_LENGTH) > (notaryRegistry[notaryAddress].deregisteredPeriod + NOTARY_LOCKUP_LENGTH)); - delete notary_registry[notary_address]; - notary_address.transfer(NOTARY_DEPOSIT); - NotaryReleased(notary_address, index); + delete notaryRegistry[notaryAddress]; + notaryAddress.transfer(NOTARY_DEPOSIT); + NotaryReleased(notaryAddress, index); return true; } - function update_notary_sample_size() private returns(bool) { - uint current_period = block.number / PERIOD_LENGTH; - require(current_period < sample_size_last_updated_period); + function updateNotarySampleSize() private returns(bool) { + uint currentPeriod = block.number / PERIOD_LENGTH; + require(currentPeriod < sampleSizeLastUpdatedPeriod); - current_period_notary_sample_size = next_period_notary_sample_size; - sample_size_last_updated_period = current_period; + currentPeriodNotarySampleSize = nextPeriodNotarySampleSize; + sampleSizeLastUpdatedPeriod = currentPeriod; return true; } - function register_proposer() public payable returns(int) { + function registerProposer() public payable returns(int) { } - function deregister_proposer() public { + function deregisterProposer() public { } - function release_proposer() public { + function releaseProposer() public { } - function proposer_add_balance(uint shard_id) payable public { + function proposerAddBalance(uint shardId) payable public { } - function proposer_withdraw_balance(uint shard_id) public { + function proposerWithdrawBalance(uint shardId) public { } function addHeader(uint _shardId, uint period, bytes32 height, - bytes32 _parent_hash, bytes32 chunk_root, - address proposer_address, uint proposer_bid, - bytes proposer_signature) public returns(bool) { - // TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, - // all others don’t. This function just emits a log + bytes32 _parentHash, bytes32 chunkRoot, + address proposerAddress, uint proposerBid, + bytes proposerSignature) public returns(bool) { + /* + TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, + all others don’t. This function just emits a log + */ } - function empty_stack() internal view returns(bool) { - return empty_slots_stack_top == 0; + function emptyStack() internal view returns(bool) { + return emptySlotsStackTop == 0; } - function stack_push(uint index) internal { - if (empty_slots_stack.length == empty_slots_stack_top) - empty_slots_stack.push(index); + function stackPush(uint index) internal { + if (emptySlotsStack.length == emptySlotsStackTop) + emptySlotsStack.push(index); else - empty_slots_stack[empty_slots_stack_top] = index; + emptySlotsStack[emptySlotsStackTop] = index; - ++empty_slots_stack_top; + ++emptySlotsStackTop; } // Pop element from stack // Caller should check if stack is empty - function stack_pop() internal returns(uint) { - require(empty_slots_stack_top > 1); - --empty_slots_stack_top; - return empty_slots_stack[empty_slots_stack_top]; + function stackPop() internal returns(uint) { + require(emptySlotsStackTop > 1); + --emptySlotsStackTop; + return emptySlotsStack[emptySlotsStackTop]; } } + + function computeHeaderHash(uint256 shardId, + bytes32 parentHash, + bytes32 chunkRoot, + uint256 period, + address proposerAddress, + uint256 proposerBid) public returns(bytes32){ + + } \ No newline at end of file From dfc0ca55cb983c1f1fd828b7a810aac8a7863f9e Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 19 Apr 2018 14:46:04 -0700 Subject: [PATCH 11/30] sharding: proposer is irrelevant for spec 1.1 Former-commit-id: ea7d8068b76b367e99948542e0153afc3e906d5d [formerly 80249c257922b26a0908aea044eee004acdd5bc9] Former-commit-id: 4483c490a8eb3f1f3eae22ad6574ce132e353b13 --- sharding/contracts/sharding_manager.sol | 61 +++---------------------- 1 file changed, 6 insertions(+), 55 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 241eb06b3..2ca2698be 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -1,37 +1,23 @@ pragma solidity ^0.4.19; contract SMC { - event HeaderAdded(uint indexed shard_id, bytes32 parent_hash, - bytes32 chunk_root, int128 period, int128 height, - address proposer_address, uint proposer_bid, - bytes proposer_signature); + event HeaderAdded(uint indexed shard_id, bytes32 chunk_root, + int128 period, address proposer_address); event NotaryRegistered(address notary, uint pool_index); event NotaryDeregistered(address notary, uint pool_index, uint deregistered_period); event NotaryReleased(address notary, uint pool_index); - event ProposerRegistered(uint pool_index); - event ProposerDeregistered(uint index); - event ProposerReleased(uint index); struct Notary { uint deregisteredPeriod; uint poolIndex; bool deposited; } - - struct Proposer { - uint deregisteredPeriod; - uint balances - } struct CollationHeader { uint shardId; // Number of the shard ID - bytes32 parentHash; // Hash of the parent collation bytes32 chunkRoot; // Root hash of the collation body uint period; // Period which header should be included - uint height; // Height of the collation address proposerAddress; - uint proposerBid; - bytes proposerSignature; } // Packed variables to be used in addHeader @@ -43,11 +29,9 @@ contract SMC { } address[] public notaryPool; - Proposer[] public proposerPool; // Notary registry (deregistered is 0 for not yet deregistered notaries) mapping (address => Notary) public notaryRegistry; - mapping (address => Proposer) public proposerRegistry; // shardId => (header_hash => tree root) mapping (uint => mapping (bytes32 => bytes32)) public collationTrees; // shardId => (headerHash => CollationHeader) @@ -77,14 +61,8 @@ contract SMC { uint constant NOTARY_DEPOSIT = 1000 ether; // The reward for notary on voting for a collation uint constant NOTARY_REWARD = 0.001 ether; - // The minimum deposit size for a proposer - uint constant PROPOSER_DEPOSIT = 1 ether; - // The minimum balance of a proposer - uint constant MIN_PROPOSER_BALANCE = 0.1 ether; // Time the ether is locked by notaries uint NOTARY_LOCKUP_LENGTH = 16128; - // Time the ether is locked by proposers - uint PROPOSER_LOCKUP_LENGTH = 48; // Number of periods ahead of current period, which the contract // is able to return the notary of that period uint constant LOOKAHEAD_LENGTH = 4; @@ -96,14 +74,10 @@ contract SMC { // Log the latest period number of the shard mapping (int => int) public periodHead; - function SMC(uint notary_lockup_length, uint proposer_lockup_length) public { + function SMC(uint notary_lockup_length) public { NOTARY_LOCKUP_LENGTH = notary_lockup_length; - PROPOSER_LOCKUP_LENGTH = proposer_lockup_length; } - event LOG(uint L); - - function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { uint currentPeriod = block.number / PERIOD_LENGTH; @@ -198,30 +172,8 @@ contract SMC { return true; } - function registerProposer() public payable returns(int) { - - } - - function deregisterProposer() public { - - } - - function releaseProposer() public { - - } - - function proposerAddBalance(uint shardId) payable public { - - } - - function proposerWithdrawBalance(uint shardId) public { - - } - - function addHeader(uint _shardId, uint period, bytes32 height, - bytes32 _parentHash, bytes32 chunkRoot, - address proposerAddress, uint proposerBid, - bytes proposerSignature) public returns(bool) { + function addHeader(uint _shardId, uint period, bytes32 chunkRoot, + address proposerAddress) public returns(bool) { /* TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, all others don’t. This function just emits a log @@ -254,7 +206,6 @@ contract SMC { bytes32 parentHash, bytes32 chunkRoot, uint256 period, - address proposerAddress, - uint256 proposerBid) public returns(bytes32){ + address proposerAddress) public returns(bytes32){ } \ No newline at end of file From 9d2be9f8678112e0aa11bb018bfd26f8e29ebb85 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 19 Apr 2018 16:47:38 -0700 Subject: [PATCH 12/30] sharding: fixed lint messages Former-commit-id: a79631df65076e8ffd6ab2cd6265a1411456356f [formerly 5f02c7f2b7f50b230e9a434a50d2d569770806ab] Former-commit-id: 2fd87aa767d8efbefdf54cdc08f49cbea0dd5b6f --- sharding/contracts/sharding_manager.sol | 370 ++++++++++++------------ 1 file changed, 183 insertions(+), 187 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 2ca2698be..a860738af 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -1,211 +1,207 @@ -pragma solidity ^0.4.19; +pragma solidity ^0.4.23; + contract SMC { - event HeaderAdded(uint indexed shard_id, bytes32 chunk_root, - int128 period, address proposer_address); - event NotaryRegistered(address notary, uint pool_index); - event NotaryDeregistered(address notary, uint pool_index, uint deregistered_period); - event NotaryReleased(address notary, uint pool_index); + event HeaderAdded(uint indexed shardId, bytes32 chunkRoot, int128 period, address proposerAddress); + event NotaryRegistered(address notary, uint poolIndex); + event NotaryDeregistered(address notary, uint poolIndex, uint deregisteredPeriod); + event NotaryReleased(address notary, uint poolIndex); - struct Notary { - uint deregisteredPeriod; - uint poolIndex; - bool deposited; - } + struct Notary { + uint deregisteredPeriod; + uint poolIndex; + bool deposited; + } - struct CollationHeader { - uint shardId; // Number of the shard ID - bytes32 chunkRoot; // Root hash of the collation body - uint period; // Period which header should be included - address proposerAddress; - } + struct CollationHeader { + uint shardId; // Number of the shard ID + bytes32 chunkRoot; // Root hash of the collation body + uint period; // Period which header should be included + address proposerAddress; + } // Packed variables to be used in addHeader - struct HeaderVars { - bytes32 entireHeaderHash; - int score; - address notaryAddr; - bool isNewHead; - } - - address[] public notaryPool; - - // Notary registry (deregistered is 0 for not yet deregistered notaries) - mapping (address => Notary) public notaryRegistry; - // shardId => (header_hash => tree root) - mapping (uint => mapping (bytes32 => bytes32)) public collationTrees; - // shardId => (headerHash => CollationHeader) - mapping (int => mapping (bytes32 => CollationHeader)) public collationHeaders; - // shardId => headerHash - mapping (int => bytes32) shardead; - - // Number of notaries - uint public notaryPoolLength; - // Indexes of empty slots caused by the function `withdraw` - uint[] emptySlotsStack; - // The top index of the stack in emptySlotsStack - uint emptySlotsStackTop; - - // Notary sample size at current period and next period - uint currentPeriodNotarySampleSize; - uint nextPeriodNotarySampleSize; - uint sampleSizeLastUpdatedPeriod; - - // Constant values - uint constant PERIOD_LENGTH = 5; - // Exact collation body size (1mb) - uint constant COLLATION_SIZE = 2 ** 20; - // Number of shards - uint constant SHARD_COUNT = 100; - // The minimum deposit size for a notary - uint constant NOTARY_DEPOSIT = 1000 ether; - // The reward for notary on voting for a collation - uint constant NOTARY_REWARD = 0.001 ether; - // Time the ether is locked by notaries - uint NOTARY_LOCKUP_LENGTH = 16128; - // Number of periods ahead of current period, which the contract - // is able to return the notary of that period - uint constant LOOKAHEAD_LENGTH = 4; - // Number of notaries to select from notary pool for each shard in each period - uint constant COMMITTEE_SIZE = 135; - // Threshold(number of notaries in committee) for a proposal to be deem accepted - uint constant QUORUM_SIZE = 90; - - // Log the latest period number of the shard - mapping (int => int) public periodHead; - - function SMC(uint notary_lockup_length) public { - NOTARY_LOCKUP_LENGTH = notary_lockup_length; - } - - function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { - uint currentPeriod = block.number / PERIOD_LENGTH; - - // Determine notary pool length based on notary sample size - uint sampleSize; - if (period > sampleSizeLastUpdatedPeriod) { - sampleSize = nextPeriodNotarySampleSize; - } else { - sampleSize = currentPeriodNotarySampleSize; + struct HeaderVars { + bytes32 entireHeaderHash; + int score; + address notaryAddr; + bool isNewHead; } - uint periodToLook = period * PERIOD_LENGTH - 1; + address[] public notaryPool; - for (uint i = 1; i <= QUORUM_SIZE; i++) { - uint index = uint(keccak256(block.blockhash(periodToLook), index)) % sampleSize; - if (notaryPool[index] == msg.sender) { + // notaryAddress => notaryStruct + mapping (address => Notary) public notaryRegistry; + // shardId => (headerHash => treeRoot) + mapping (uint => mapping (bytes32 => bytes32)) public collationTrees; + // shardId => (headerHash => collationHeader) + mapping (int => mapping (bytes32 => CollationHeader)) public collationHeaders; + // shardId => headerHash + mapping (int => bytes32) shardHead; + + // Number of notaries + uint public notaryPoolLength; + // Stack of empty notary slot indicies + uint[] emptySlotsStack; + // Top index of the stack + uint emptySlotsStackTop; + + // Notary sample size at current period and next period + uint currentPeriodNotarySampleSize; + uint nextPeriodNotarySampleSize; + uint sampleSizeLastUpdatedPeriod; + + // Constant values + uint constant PERIOD_LENGTH = 5; + // Exact collation body size (1mb) + uint constant COLLATION_SIZE = 2 ** 20; + // Number of shards + uint constant SHARD_COUNT = 100; + // The minimum deposit size for a notary + uint constant NOTARY_DEPOSIT = 1000 ether; + // The reward for notary on voting for a collation + uint constant NOTARY_REWARD = 0.001 ether; + // Time the ether is locked by notaries + uint constant NOTARY_LOCKUP_LENGTH = 16128; + // Number of periods ahead of current period, which the contract + // is able to return the notary of that period + uint constant LOOKAHEAD_LENGTH = 4; + // Number of notaries to select from notary pool for each shard in each period + uint constant COMMITTEE_SIZE = 135; + // Threshold(number of notaries in committee) for a proposal to be accepted + uint constant QUORUM_SIZE = 90; + + // Log the latest period number of the shard + mapping (int => int) public periodHead; + + function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { + uint currentPeriod = block.number / PERIOD_LENGTH; + + // Determine notary pool length based on notary sample size + uint sampleSize; + if (period > sampleSizeLastUpdatedPeriod) { + sampleSize = nextPeriodNotarySampleSize; + } else { + sampleSize = currentPeriodNotarySampleSize; + } + + // Get the most recent block number before the period started + uint latestBlock = period * PERIOD_LENGTH - 1; + + for (uint i = 0; i < QUORUM_SIZE; i++) { + uint index = uint(keccak256(block.blockhash(latestBlock), index)) % sampleSize; + if (notaryPool[index] == msg.sender) { + return true; + } + } + return false; + } + + function registerNotary() public payable returns(bool) { + address notaryAddress = msg.sender; + require(!notaryRegistry[notaryAddress].deposited); + require(msg.value == NOTARY_DEPOSIT); + + updateNotarySampleSize(); + + uint index; + if (emptyStack()) { + index = notaryPoolLength; + notaryPool.push(notaryAddress); + } else { + index = stackPop(); + notaryPool[index] = notaryAddress; + } + ++notaryPoolLength; + + notaryRegistry[notaryAddress] = Notary({ + deregisteredPeriod: 0, + poolIndex: index, + deposited: true + }); + + // if current index is greater than notary sample size, increase notary sample size for next period + if (index >= nextPeriodNotarySampleSize) { + nextPeriodNotarySampleSize = index + 1; + } + + emit NotaryRegistered(notaryAddress, index); return true; - } - } - return false; - } - - function registerNotary() public payable returns(bool) { - address notaryAddress = msg.sender; - require(!notaryRegistry[notaryAddress].deposited); - require(msg.value == NOTARY_DEPOSIT); - - updateNotarySampleSize(); - - uint index; - if (!emptyStack()) { - index = stackPop(); - notaryPool[index] = notaryAddress; - } - else { - index = notaryPoolLength; - notaryPool.push(notaryAddress); - } - ++notaryPoolLength; - - notaryRegistry[notaryAddress] = Notary({ - deregisteredPeriod: 0, - poolIndex: index, - deposited: true - }); - - // if current index is greater than notary sample size, increase notary sample size for next period - if (index >= nextPeriodNotarySampleSize) { - nextPeriodNotarySampleSize = index + 1; } - NotaryRegistered(notaryAddress, index); - return true; - } + function deregisterNotary() public returns(bool) { + address notaryAddress = msg.sender; + uint index = notaryRegistry[notaryAddress].poolIndex; + require(notaryRegistry[notaryAddress].deposited); + require(notaryPool[index] == notaryAddress); - function deregisterNotary() public returns(bool) { - address notaryAddress = msg.sender; - uint index = notaryRegistry[notaryAddress].poolIndex; - require(notaryRegistry[notaryAddress].deposited); - require(notaryPool[index] == notaryAddress); + updateNotarySampleSize(); + + uint deregisteredPeriod = block.number / PERIOD_LENGTH; + notaryRegistry[notaryAddress].deregisteredPeriod = deregisteredPeriod; - updateNotarySampleSize(); - - uint deregisteredPeriod = block.number / PERIOD_LENGTH; - notaryRegistry[notaryAddress].deregisteredPeriod = deregisteredPeriod; + stackPush(index); + --notaryPoolLength; + emit NotaryDeregistered(notaryAddress, index, deregisteredPeriod); + return true; + } - stackPush(index); - --notaryPoolLength; - NotaryDeregistered(notaryAddress, index, deregisteredPeriod); - return true; - } + function releaseNotary() public returns(bool) { + address notaryAddress = msg.sender; + uint index = notaryRegistry[notaryAddress].poolIndex; + require(notaryRegistry[notaryAddress].deposited == true); + require(notaryRegistry[notaryAddress].deregisteredPeriod != 0); + require((block.number / PERIOD_LENGTH) > + (notaryRegistry[notaryAddress].deregisteredPeriod + NOTARY_LOCKUP_LENGTH)); - function releaseNotary() public returns(bool) { - address notaryAddress = msg.sender; - uint index = notaryRegistry[notaryAddress].poolIndex; - require(notaryRegistry[notaryAddress].deposited == true); - require(notaryRegistry[notaryAddress].deregisteredPeriod != 0); - require((block.number / PERIOD_LENGTH) > (notaryRegistry[notaryAddress].deregisteredPeriod + NOTARY_LOCKUP_LENGTH)); + delete notaryRegistry[notaryAddress]; + notaryAddress.transfer(NOTARY_DEPOSIT); + emit NotaryReleased(notaryAddress, index); + return true; + } - delete notaryRegistry[notaryAddress]; - notaryAddress.transfer(NOTARY_DEPOSIT); - NotaryReleased(notaryAddress, index); - return true; - } + function computeHeaderHash(uint256 shardId, bytes32 parentHash, + bytes32 chunkRoot, uint256 period, address proposerAddress) + public returns(bytes32) { + /* + TODO: Calculate the hash of the collation header from the input parameters + */ + } - function updateNotarySampleSize() private returns(bool) { - uint currentPeriod = block.number / PERIOD_LENGTH; - require(currentPeriod < sampleSizeLastUpdatedPeriod); + function addHeader(uint _shardId, uint period, bytes32 chunkRoot, + address proposerAddress) public returns(bool) { + /* + TODO: Anyone can call this at any time. The first header + to get included for a given shard in a given period gets in, + all others don’t. This function just emits a log + */ + } - currentPeriodNotarySampleSize = nextPeriodNotarySampleSize; - sampleSizeLastUpdatedPeriod = currentPeriod; - return true; - } + function updateNotarySampleSize() internal returns(bool) { + uint currentPeriod = block.number / PERIOD_LENGTH; + require(currentPeriod < sampleSizeLastUpdatedPeriod); - function addHeader(uint _shardId, uint period, bytes32 chunkRoot, - address proposerAddress) public returns(bool) { - /* - TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, - all others don’t. This function just emits a log - */ - } + currentPeriodNotarySampleSize = nextPeriodNotarySampleSize; + sampleSizeLastUpdatedPeriod = currentPeriod; + return true; + } + function emptyStack() internal view returns(bool) { + return emptySlotsStackTop == 0; + } - function emptyStack() internal view returns(bool) { - return emptySlotsStackTop == 0; - } + function stackPush(uint index) internal { + if (emptySlotsStack.length == emptySlotsStackTop) + emptySlotsStack.push(index); + else + emptySlotsStack[emptySlotsStackTop] = index; - function stackPush(uint index) internal { - if (emptySlotsStack.length == emptySlotsStackTop) - emptySlotsStack.push(index); - else - emptySlotsStack[emptySlotsStackTop] = index; + ++emptySlotsStackTop; + } - ++emptySlotsStackTop; - } - // Pop element from stack - // Caller should check if stack is empty - function stackPop() internal returns(uint) { - require(emptySlotsStackTop > 1); - --emptySlotsStackTop; - return emptySlotsStack[emptySlotsStackTop]; - } -} - - function computeHeaderHash(uint256 shardId, - bytes32 parentHash, - bytes32 chunkRoot, - uint256 period, - address proposerAddress) public returns(bytes32){ - - } \ No newline at end of file + function stackPop() internal returns(uint) { + require(emptySlotsStackTop > 1); + --emptySlotsStackTop; + return emptySlotsStack[emptySlotsStackTop]; + } +} \ No newline at end of file From d45e45f543c78b69b21f4cb3c0093cd462fc2f8d Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 19 Apr 2018 23:41:52 -0700 Subject: [PATCH 13/30] sharding: functions descriptions Former-commit-id: ea79f98f18b2f001c8b0c9579926d7c2de4e45c8 [formerly 2bafc5faedc0dba69799629bd55d17683e06a583] Former-commit-id: 609f9f31e1b6cebb515300f5c8672c15ae2003c1 --- sharding/contracts/sharding_manager.sol | 41 +++++++++++++++++++------ 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index a860738af..f1579142d 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -53,8 +53,6 @@ contract SMC { // Constant values uint constant PERIOD_LENGTH = 5; - // Exact collation body size (1mb) - uint constant COLLATION_SIZE = 2 ** 20; // Number of shards uint constant SHARD_COUNT = 100; // The minimum deposit size for a notary @@ -74,6 +72,8 @@ contract SMC { // Log the latest period number of the shard mapping (int => int) public periodHead; + /// Checks if a notary with given shard id and period has been chosen as + /// a committee member to vote for header added on to the main chain function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { uint currentPeriod = block.number / PERIOD_LENGTH; @@ -97,11 +97,14 @@ contract SMC { return false; } + /// Registers notary to notatery registry, locks in the notary deposit, + /// and returns true on success function registerNotary() public payable returns(bool) { address notaryAddress = msg.sender; require(!notaryRegistry[notaryAddress].deposited); require(msg.value == NOTARY_DEPOSIT); + // Track the numbers of participating notaries in between periods updateNotarySampleSize(); uint index; @@ -129,12 +132,16 @@ contract SMC { return true; } + /// Deregisters notary from notatery registry, lock up period countdowns down, + /// notary may call releaseNotary after lock up period finishses to withdraw deposit, + /// and returns true on success function deregisterNotary() public returns(bool) { address notaryAddress = msg.sender; uint index = notaryRegistry[notaryAddress].poolIndex; require(notaryRegistry[notaryAddress].deposited); require(notaryPool[index] == notaryAddress); + // Track the numbers of participating notaries in between periods updateNotarySampleSize(); uint deregisteredPeriod = block.number / PERIOD_LENGTH; @@ -146,13 +153,14 @@ contract SMC { return true; } + /// Removes an entry from notary registry, returns deposit back to the notary, + /// and returns true on success. function releaseNotary() public returns(bool) { address notaryAddress = msg.sender; uint index = notaryRegistry[notaryAddress].poolIndex; require(notaryRegistry[notaryAddress].deposited == true); require(notaryRegistry[notaryAddress].deregisteredPeriod != 0); - require((block.number / PERIOD_LENGTH) > - (notaryRegistry[notaryAddress].deregisteredPeriod + NOTARY_LOCKUP_LENGTH)); + require((block.number / PERIOD_LENGTH) > (notaryRegistry[notaryAddress].deregisteredPeriod + NOTARY_LOCKUP_LENGTH)); delete notaryRegistry[notaryAddress]; notaryAddress.transfer(NOTARY_DEPOSIT); @@ -160,16 +168,26 @@ contract SMC { return true; } - function computeHeaderHash(uint256 shardId, bytes32 parentHash, - bytes32 chunkRoot, uint256 period, address proposerAddress) - public returns(bytes32) { + /// Calcuates the hash of the header from the input parameters + function computeHeaderHash( + uint256 shardId, + bytes32 parentHash, + bytes32 chunkRoot, + uint256 period, + address proposerAddress + ) public returns(bytes32) { /* TODO: Calculate the hash of the collation header from the input parameters */ } - function addHeader(uint _shardId, uint period, bytes32 chunkRoot, - address proposerAddress) public returns(bool) { + /// Add collation header to the main chain, anyone can call this function. It emits a log + function addHeader( + uint _shardId, + uint period, + bytes32 chunkRoot, + address proposerAddress + ) public returns(bool) { /* TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, @@ -177,6 +195,8 @@ contract SMC { */ } + /// To keep track of notary size in between periods, we call updateNotarySampleSize + /// before notary registration/deregistration so correct size can be applied next period function updateNotarySampleSize() internal returns(bool) { uint currentPeriod = block.number / PERIOD_LENGTH; require(currentPeriod < sampleSizeLastUpdatedPeriod); @@ -186,10 +206,12 @@ contract SMC { return true; } + /// Check if the empty slots stack is empty function emptyStack() internal view returns(bool) { return emptySlotsStackTop == 0; } + /// Save one uint into the empty slots stack for notary to use later function stackPush(uint index) internal { if (emptySlotsStack.length == emptySlotsStackTop) emptySlotsStack.push(index); @@ -199,6 +221,7 @@ contract SMC { ++emptySlotsStackTop; } + /// Get one uint out of the empty slots stack for notary index function stackPop() internal returns(uint) { require(emptySlotsStackTop > 1); --emptySlotsStackTop; From b54a20281ed41c0402ae245c20da9060a116e916 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Fri, 20 Apr 2018 15:08:52 -0700 Subject: [PATCH 14/30] sharding: fixed notary tests Former-commit-id: 9ba590940143b0de2068c8dfe4233d221d8148dc [formerly b6cefd256e5f0d2db0f8284932ada4a5e4804212] Former-commit-id: 4aa404a5fd760990ecc4414360e7b02c068a882a --- sharding/contracts/sharding_manager_test.go | 115 ++++++++++---------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 9b5941f01..b2255324d 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -14,16 +14,16 @@ import ( ) type SMCConfig struct { - collatorLockupLenght *big.Int + notaryLockupLenght *big.Int proposerLockupLength *big.Int } var ( mainKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - accountBalance1001Eth, _ = new(big.Int).SetString("1001000000000000000000", 10) - collatorDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) + accountBalance1001Eth, _ = new(big.Int).SetString("5000000000000000000000", 10) + notaryDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) smcConfig = SMCConfig{ - collatorLockupLenght: new(big.Int).SetInt64(1), + notaryLockupLenght: new(big.Int).SetInt64(1), proposerLockupLength: new(big.Int).SetInt64(1), } ) @@ -31,7 +31,7 @@ var ( func deploySMCContract(backend *backends.SimulatedBackend, key *ecdsa.PrivateKey) (common.Address, *types.Transaction, *SMC, error) { transactOpts := bind.NewKeyedTransactor(key) defer backend.Commit() - return DeploySMC(transactOpts, backend, smcConfig.collatorLockupLenght, smcConfig.proposerLockupLength) + return DeploySMC(transactOpts, backend) } // Test creating the SMC contract @@ -45,113 +45,114 @@ func TestContractCreation(t *testing.T) { } } -// Test register collator -func TestCollatorDeposit(t *testing.T) { +// Test register notary +func TestNotaryDeposit(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) transactOpts := bind.NewKeyedTransactor(mainKey) _, _, smc, _ := deploySMCContract(backend, mainKey) - // Test register_collator() function + // Test register_notary() function // Deposit 1000 Eth - transactOpts.Value = collatorDeposit + transactOpts.Value = notaryDeposit - if _, err := smc.Register_collator(transactOpts); err != nil { - t.Fatalf("Collator cannot deposit: %v", err) + t.Log(transactOpts.) + if _, err := smc.RegisterNotary(transactOpts); err != nil { + t.Fatalf("Notary cannot deposit: %v", err) } backend.Commit() - // Check updated number of collators - numCollators, err := smc.Collator_pool_len(&bind.CallOpts{}) + // Check updated number of notaries + numNotaries, err := smc.NotaryPoolLength(&bind.CallOpts{}) if err != nil { - t.Fatalf("Failed to get collator pool length: %v", err) + t.Fatalf("Failed to get notary pool length: %v", err) } - if numCollators.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Failed to update number of collators") + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Failed to update number of notaries") } // Check deposited is true - tx, err := smc.Collator_registry(&bind.CallOpts{}, addr) + tx, err := smc.NotaryRegistry(&bind.CallOpts{}, addr) if err != nil { - t.Fatalf("Failed to update collator registry: %v", err) + t.Fatalf("Failed to update notary registry: %v", err) } if tx.Deposited != true { - t.Fatalf("Collator registry not updated") + t.Fatalf("Notary registry not updated") } - // Check for the RegisterCollator event - depositsEventsIterator, err := smc.FilterCollatorRegistered(&bind.FilterOpts{}) + // Check for the RegisterNotary event + depositsEventsIterator, err := smc.FilterNotaryRegistered(&bind.FilterOpts{}) if err != nil { t.Fatalf("Failed to get Deposit event: %v", err) } if !depositsEventsIterator.Next() { t.Fatal("No Deposit event found") } - if depositsEventsIterator.Event.Collator != addr { - t.Fatalf("Collator address mismatch: %x should be %x", depositsEventsIterator.Event.Collator, addr) + if depositsEventsIterator.Event.Notary != addr { + t.Fatalf("Notary address mismatch: %x should be %x", depositsEventsIterator.Event.Notary, addr) } - if depositsEventsIterator.Event.Pool_index.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Collator index mismatch: %d should be 0", depositsEventsIterator.Event.Pool_index) + if depositsEventsIterator.Event.PoolIndex.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Notary index mismatch: %d should be 0", depositsEventsIterator.Event.PoolIndex) } } -// Test collator deregister from pool -func TestCollatorDeregister(t *testing.T) { +// Test notary deregister from pool +func TestNotaryDeregister(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) transactOpts := bind.NewKeyedTransactor(mainKey) _, _, smc, _ := deploySMCContract(backend, mainKey) - transactOpts.Value = collatorDeposit - // Register collator - smc.Register_collator(transactOpts) + transactOpts.Value = notaryDeposit + // Register notary + smc.RegisterNotary(transactOpts) transactOpts.Value = big.NewInt(0) - // Deregister collator - _, err := smc.Deregister_collator(transactOpts) + // Deregister notary + _, err := smc.DeregisterNotary(transactOpts) backend.Commit() if err != nil { - t.Fatalf("Failed to deregister collator: %v", err) + t.Fatalf("Failed to deregister notary: %v", err) } - // Check for the CollatorDeregistered event - withdrawsEventsIterator, err := smc.FilterCollatorDeregistered(&bind.FilterOpts{Start: 0}) + // Check for the NotaryDeregistered event + withdrawsEventsIterator, err := smc.FilterNotaryDeregistered(&bind.FilterOpts{Start: 0}) if err != nil { - t.Fatalf("Failed to get CollatorDeregistered event: %v", err) + t.Fatalf("Failed to get NotaryDeregistered event: %v", err) } if !withdrawsEventsIterator.Next() { - t.Fatal("No CollatorDeregistered event found") + t.Fatal("No NotaryDeregistered event found") } - if withdrawsEventsIterator.Event.Pool_index.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Collator index mismatch: %d should be 0", withdrawsEventsIterator.Event.Pool_index) + if withdrawsEventsIterator.Event.PoolIndex.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Notary index mismatch: %d should be 0", withdrawsEventsIterator.Event.PoolIndex) } } -func TestGetEligibleCollator(t *testing.T) { - const numberCollators = 20 - var collatorPoolAddr [numberCollators]common.Address - var collatorPoolPrivKeys [numberCollators]*ecdsa.PrivateKey - var transactOpts [numberCollators]*bind.TransactOpts +func TestGetEligibleNotary(t *testing.T) { + const numberNotaries = 20 + var notaryPoolAddr [numberNotaries]common.Address + var notaryPoolPrivKeys [numberNotaries]*ecdsa.PrivateKey + var transactOpts [numberNotaries]*bind.TransactOpts genesis := make(core.GenesisAlloc) - for i := 0; i < numberCollators; i++ { + for i := 0; i < numberNotaries; i++ { key, _ := crypto.GenerateKey() - collatorPoolPrivKeys[i] = key - collatorPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) + notaryPoolPrivKeys[i] = key + notaryPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) transactOpts[i] = bind.NewKeyedTransactor(key) - transactOpts[i].Value = collatorDeposit + transactOpts[i].Value = notaryDeposit - genesis[collatorPoolAddr[i]] = core.GenesisAccount{ + genesis[notaryPoolAddr[i]] = core.GenesisAccount{ Balance: accountBalance1001Eth, } } backend := backends.NewSimulatedBackend(genesis) - _, _, smc, _ := deploySMCContract(backend, collatorPoolPrivKeys[0]) + _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) - // Register collator - for i := 0; i < numberCollators; i++ { - smc.Register_collator(transactOpts[i]) + // Register notary + for i := 0; i < numberNotaries; i++ { + smc.RegisterNotary(transactOpts[i]) } // Move blockchain 4 blocks further (Head is at 5 after) : period 1 @@ -159,16 +160,16 @@ func TestGetEligibleCollator(t *testing.T) { backend.Commit() } - _, err := smc.Get_eligible_collator(&bind.CallOpts{}, big.NewInt(0), big.NewInt(4)) + _, err := smc.IsNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(4)) if err != nil { - t.Fatalf("Cannot get eligible collator: %v", err) + t.Fatalf("Cannot get eligible notary: %v", err) } // after: Head is 11, period 2 for i := 0; i < 6; i++ { backend.Commit() } - _, err = smc.Get_eligible_collator(&bind.CallOpts{}, big.NewInt(1), big.NewInt(6)) + _, err = smc.IsNotaryInCommittee(&bind.CallOpts{}, big.NewInt(1), big.NewInt(6)) if err != nil { - t.Fatalf("Cannot get eligible collator: %v\n", err) + t.Fatalf("Cannot get eligible notary: %v\n", err) } } From 0d9523dcd4cd868654acb2ead599ffa87d77548f Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Fri, 20 Apr 2018 16:14:16 -0700 Subject: [PATCH 15/30] sharding: fixed notary sample function Former-commit-id: 608025faad454e517fd144759886e04113805907 [formerly 5b753cdef5fc3f4f4f585e972ba624a42d21c672] Former-commit-id: 8125d538d91209971860ed637b456ff07dff8151 --- sharding/contracts/sharding_manager.sol | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index f1579142d..5d976ac99 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -72,7 +72,7 @@ contract SMC { // Log the latest period number of the shard mapping (int => int) public periodHead; - /// Checks if a notary with given shard id and period has been chosen as + /// Checks if a notary with given shard id and period has been chosen as /// a committee member to vote for header added on to the main chain function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { uint currentPeriod = block.number / PERIOD_LENGTH; @@ -94,7 +94,7 @@ contract SMC { return true; } } - return false; + return false; } /// Registers notary to notatery registry, locks in the notary deposit, @@ -106,11 +106,11 @@ contract SMC { // Track the numbers of participating notaries in between periods updateNotarySampleSize(); - + uint index; if (emptyStack()) { - index = notaryPoolLength; - notaryPool.push(notaryAddress); + index = notaryPoolLength; + notaryPool.push(notaryAddress); } else { index = stackPop(); notaryPool[index] = notaryAddress; @@ -127,7 +127,7 @@ contract SMC { if (index >= nextPeriodNotarySampleSize) { nextPeriodNotarySampleSize = index + 1; } - + emit NotaryRegistered(notaryAddress, index); return true; } @@ -143,7 +143,7 @@ contract SMC { // Track the numbers of participating notaries in between periods updateNotarySampleSize(); - + uint deregisteredPeriod = block.number / PERIOD_LENGTH; notaryRegistry[notaryAddress].deregisteredPeriod = deregisteredPeriod; @@ -171,7 +171,7 @@ contract SMC { /// Calcuates the hash of the header from the input parameters function computeHeaderHash( uint256 shardId, - bytes32 parentHash, + bytes32 parentHash, bytes32 chunkRoot, uint256 period, address proposerAddress @@ -185,7 +185,7 @@ contract SMC { function addHeader( uint _shardId, uint period, - bytes32 chunkRoot, + bytes32 chunkRoot, address proposerAddress ) public returns(bool) { /* @@ -199,8 +199,9 @@ contract SMC { /// before notary registration/deregistration so correct size can be applied next period function updateNotarySampleSize() internal returns(bool) { uint currentPeriod = block.number / PERIOD_LENGTH; - require(currentPeriod < sampleSizeLastUpdatedPeriod); - + if (currentPeriod < sampleSizeLastUpdatedPeriod) { + return false; + } currentPeriodNotarySampleSize = nextPeriodNotarySampleSize; sampleSizeLastUpdatedPeriod = currentPeriod; return true; @@ -226,5 +227,5 @@ contract SMC { require(emptySlotsStackTop > 1); --emptySlotsStackTop; return emptySlotsStack[emptySlotsStackTop]; - } + } } \ No newline at end of file From 8a10e4efa267d8034d61fd6e637f6e507e0d305f Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Sat, 21 Apr 2018 16:57:13 -0700 Subject: [PATCH 16/30] sharding: added test cases for registering notary Former-commit-id: dad6acfd8273a5fce14a635999c145776727a50b [formerly 3d88c2eca4e930e07d76c2d28b2122408eb9b734] Former-commit-id: ea652d4701ba898e007604d9c1e1ae6c94949072 --- sharding/contracts/sharding_manager_test.go | 286 ++++++++++++-------- 1 file changed, 175 insertions(+), 111 deletions(-) diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index b2255324d..02728c5be 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -11,19 +11,21 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/sharding" ) type SMCConfig struct { - notaryLockupLenght *big.Int + notaryLockupLenght *big.Int proposerLockupLength *big.Int } var ( - mainKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - accountBalance1001Eth, _ = new(big.Int).SetString("5000000000000000000000", 10) - notaryDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) - smcConfig = SMCConfig{ - notaryLockupLenght: new(big.Int).SetInt64(1), + mainKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") + accountBalance1001Eth, _ = new(big.Int).SetString("1001000000000000000000", 10) + notaryDepositInsufficient, _ = new(big.Int).SetString("999000000000000000000", 10) + notaryDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) + smcConfig = SMCConfig{ + notaryLockupLenght: new(big.Int).SetInt64(1), proposerLockupLength: new(big.Int).SetInt64(1), } ) @@ -46,102 +48,19 @@ func TestContractCreation(t *testing.T) { } // Test register notary -func TestNotaryDeposit(t *testing.T) { - addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - transactOpts := bind.NewKeyedTransactor(mainKey) - _, _, smc, _ := deploySMCContract(backend, mainKey) - - // Test register_notary() function - // Deposit 1000 Eth - transactOpts.Value = notaryDeposit - - t.Log(transactOpts.) - if _, err := smc.RegisterNotary(transactOpts); err != nil { - t.Fatalf("Notary cannot deposit: %v", err) - } - backend.Commit() - - // Check updated number of notaries - numNotaries, err := smc.NotaryPoolLength(&bind.CallOpts{}) - if err != nil { - t.Fatalf("Failed to get notary pool length: %v", err) - } - if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Failed to update number of notaries") - } - - // Check deposited is true - tx, err := smc.NotaryRegistry(&bind.CallOpts{}, addr) - if err != nil { - t.Fatalf("Failed to update notary registry: %v", err) - } - if tx.Deposited != true { - t.Fatalf("Notary registry not updated") - } - - // Check for the RegisterNotary event - depositsEventsIterator, err := smc.FilterNotaryRegistered(&bind.FilterOpts{}) - if err != nil { - t.Fatalf("Failed to get Deposit event: %v", err) - } - if !depositsEventsIterator.Next() { - t.Fatal("No Deposit event found") - } - if depositsEventsIterator.Event.Notary != addr { - t.Fatalf("Notary address mismatch: %x should be %x", depositsEventsIterator.Event.Notary, addr) - } - if depositsEventsIterator.Event.PoolIndex.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Notary index mismatch: %d should be 0", depositsEventsIterator.Event.PoolIndex) - } -} - -// Test notary deregister from pool -func TestNotaryDeregister(t *testing.T) { - addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) - transactOpts := bind.NewKeyedTransactor(mainKey) - _, _, smc, _ := deploySMCContract(backend, mainKey) - - transactOpts.Value = notaryDeposit - // Register notary - smc.RegisterNotary(transactOpts) - - transactOpts.Value = big.NewInt(0) - // Deregister notary - _, err := smc.DeregisterNotary(transactOpts) - backend.Commit() - if err != nil { - t.Fatalf("Failed to deregister notary: %v", err) - } - - // Check for the NotaryDeregistered event - withdrawsEventsIterator, err := smc.FilterNotaryDeregistered(&bind.FilterOpts{Start: 0}) - if err != nil { - t.Fatalf("Failed to get NotaryDeregistered event: %v", err) - } - if !withdrawsEventsIterator.Next() { - t.Fatal("No NotaryDeregistered event found") - } - if withdrawsEventsIterator.Event.PoolIndex.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Notary index mismatch: %d should be 0", withdrawsEventsIterator.Event.PoolIndex) - } -} - -func TestGetEligibleNotary(t *testing.T) { - const numberNotaries = 20 - var notaryPoolAddr [numberNotaries]common.Address - var notaryPoolPrivKeys [numberNotaries]*ecdsa.PrivateKey - var transactOpts [numberNotaries]*bind.TransactOpts +func TestNotaryRegister(t *testing.T) { + const notaryCount = 3 + var notaryPoolAddr [notaryCount]common.Address + var notaryPoolPrivKeys [notaryCount]*ecdsa.PrivateKey + var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) - for i := 0; i < numberNotaries; i++ { + for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key notaryPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) - transactOpts[i] = bind.NewKeyedTransactor(key) - transactOpts[i].Value = notaryDeposit - + txOpts[i] = bind.NewKeyedTransactor(key) + txOpts[i].Value = notaryDeposit genesis[notaryPoolAddr[i]] = core.GenesisAccount{ Balance: accountBalance1001Eth, } @@ -150,26 +69,171 @@ func TestGetEligibleNotary(t *testing.T) { backend := backends.NewSimulatedBackend(genesis) _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) - // Register notary - for i := 0; i < numberNotaries; i++ { - smc.RegisterNotary(transactOpts[i]) + // Test notary 0 has not registered + notary, err := smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[0]) + if err != nil { + t.Fatalf("Can't get notary registry info: %v", err) } - // Move blockchain 4 blocks further (Head is at 5 after) : period 1 - for i := 0; i < 4; i++ { - backend.Commit() + if notary.Deposited != false { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } - _, err := smc.IsNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(4)) - if err != nil { - t.Fatalf("Cannot get eligible notary: %v", err) + // Test notary 0 has registered + if _, err := smc.RegisterNotary(txOpts[0]); err != nil { + t.Fatalf("Registering notary has failed: %v", err) } - // after: Head is 11, period 2 - for i := 0; i < 6; i++ { - backend.Commit() + backend.Commit() + + notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[0]) + + if notary.Deposited != true && + notary.PoolIndex.Cmp(big.NewInt(0)) != 0 && + notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect notary registry. Want - deposited:true, index:0, period:0"+ + "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) } - _, err = smc.IsNotaryInCommittee(&bind.CallOpts{}, big.NewInt(1), big.NewInt(6)) + + // Test notary 1 and 2 have registered + if _, err := smc.RegisterNotary(txOpts[1]); err != nil { + t.Fatalf("Registering notary has failed: %v", err) + } + backend.Commit() + + if _, err := smc.RegisterNotary(txOpts[2]); err != nil { + t.Fatalf("Registering notary has failed: %v", err) + } + backend.Commit() + + notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[1]) + + if notary.Deposited != true && + notary.PoolIndex.Cmp(big.NewInt(1)) != 0 && + notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect notary registry. Want - deposited:true, index:1, period:0"+ + "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) + } + + notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[2]) + + if notary.Deposited != true && + notary.PoolIndex.Cmp(big.NewInt(2)) != 0 && + notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect notary registry. Want - deposited:true, index:2, period:0"+ + "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) + } + + // Check total numbers of notaries in pool + numNotaries, err := smc.NotaryPoolLength(&bind.CallOpts{}) if err != nil { - t.Fatalf("Cannot get eligible notary: %v\n", err) + t.Fatalf("Failed to get notary pool length: %v", err) + } + if numNotaries.Cmp(big.NewInt(3)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 3, Got: %v", numNotaries) + } +} + +func TestNotaryRegisterWithoutEnoughEther(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDepositInsufficient + _, _, smc, _ := deploySMCContract(backend, mainKey) + + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != false { + t.Fatalf("Notary deposited with insufficient fund") + } + + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + } +} + +func TestNotaryDoubleRegisters(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDeposit + _, _, smc, _ := deploySMCContract(backend, mainKey) + + // Notary 0 registers + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != true { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + } + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + // Notary 0 registers again + _, _ = smc.RegisterNotary(txOpts) + backend.Commit() + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + //ctx := context.Background() + //_, _ = backend.TransactionReceipt(ctx, tx.Hash()) + ////t.Log(r.CumulativeGasUsed) + +} + +func TestNotaryDeregisters(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDeposit + _, _, smc, _ := deploySMCContract(backend, mainKey) + + // Notary 0 registers + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != true { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + } + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + // Fast forward 100 blocks + for i := 0; i < 100; i++ { + backend.Commit() + } + + txOpts = bind.NewKeyedTransactor(mainKey) + _, err := smc.DeregisterNotary(txOpts) + if err != nil { + t.Fatalf("Failed to deregister notary: %v", err) + } + backend.Commit() + + // Verify notary has saved deregister period as (current block number / period length) + notary, _ = smc.NotaryRegistry(&bind.CallOpts{}, addr) + currentPeriod := big.NewInt(int64(100 / sharding.PeriodLength)) + if currentPeriod.Cmp(notary.DeregisteredPeriod) != 0 { + t.Fatalf("Incorrect notary degister period. Want: %v, Got: %v ", currentPeriod, notary.DeregisteredPeriod) + } + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } } From eb3f491cf86c5ea74185010a6ee0eba9d99d2da7 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Mon, 23 Apr 2018 16:18:07 -0700 Subject: [PATCH 17/30] sharding: added notary tests for degistration and release Former-commit-id: 2c76a184836468e95f5893fcd736420e89769e37 [formerly 01c871c359c0cf74866c9c5738f1574d89610c9c] Former-commit-id: 49a841231ed673421fca98d9bb54876b1e271ce0 --- sharding/contracts/sharding_manager_test.go | 195 +++++++++++++++++++- 1 file changed, 186 insertions(+), 9 deletions(-) diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 02728c5be..4848941e4 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -5,6 +5,7 @@ import ( "math/big" "testing" + "context" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" @@ -21,13 +22,14 @@ type SMCConfig struct { var ( mainKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - accountBalance1001Eth, _ = new(big.Int).SetString("1001000000000000000000", 10) + accountBalance2000Eth, _ = new(big.Int).SetString("2000000000000000000000", 10) notaryDepositInsufficient, _ = new(big.Int).SetString("999000000000000000000", 10) notaryDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) smcConfig = SMCConfig{ notaryLockupLenght: new(big.Int).SetInt64(1), proposerLockupLength: new(big.Int).SetInt64(1), } + ctx = context.Background() ) func deploySMCContract(backend *backends.SimulatedBackend, key *ecdsa.PrivateKey) (common.Address, *types.Transaction, *SMC, error) { @@ -39,7 +41,7 @@ func deploySMCContract(backend *backends.SimulatedBackend, key *ecdsa.PrivateKey // Test creating the SMC contract func TestContractCreation(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) _, _, _, err := deploySMCContract(backend, mainKey) backend.Commit() if err != nil { @@ -62,7 +64,7 @@ func TestNotaryRegister(t *testing.T) { txOpts[i] = bind.NewKeyedTransactor(key) txOpts[i].Value = notaryDeposit genesis[notaryPoolAddr[i]] = core.GenesisAccount{ - Balance: accountBalance1001Eth, + Balance: accountBalance2000Eth, } } @@ -133,9 +135,9 @@ func TestNotaryRegister(t *testing.T) { } } -func TestNotaryRegisterWithoutEnoughEther(t *testing.T) { +func TestNotaryRegisterInsufficientEther(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) txOpts := bind.NewKeyedTransactor(mainKey) txOpts.Value = notaryDepositInsufficient _, _, smc, _ := deploySMCContract(backend, mainKey) @@ -157,7 +159,7 @@ func TestNotaryRegisterWithoutEnoughEther(t *testing.T) { func TestNotaryDoubleRegisters(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) txOpts := bind.NewKeyedTransactor(mainKey) txOpts.Value = notaryDeposit _, _, smc, _ := deploySMCContract(backend, mainKey) @@ -191,9 +193,9 @@ func TestNotaryDoubleRegisters(t *testing.T) { } -func TestNotaryDeregisters(t *testing.T) { +func TestNotaryDeregister(t *testing.T) { addr := crypto.PubkeyToAddress(mainKey.PublicKey) - backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance1001Eth}}) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) txOpts := bind.NewKeyedTransactor(mainKey) txOpts.Value = notaryDeposit _, _, smc, _ := deploySMCContract(backend, mainKey) @@ -218,6 +220,7 @@ func TestNotaryDeregisters(t *testing.T) { backend.Commit() } + // Notary 0 deregisters txOpts = bind.NewKeyedTransactor(mainKey) _, err := smc.DeregisterNotary(txOpts) if err != nil { @@ -225,7 +228,7 @@ func TestNotaryDeregisters(t *testing.T) { } backend.Commit() - // Verify notary has saved deregister period as (current block number / period length) + // Verify notary has saved the deregistered period as: current block number / period length notary, _ = smc.NotaryRegistry(&bind.CallOpts{}, addr) currentPeriod := big.NewInt(int64(100 / sharding.PeriodLength)) if currentPeriod.Cmp(notary.DeregisteredPeriod) != 0 { @@ -237,3 +240,177 @@ func TestNotaryDeregisters(t *testing.T) { t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } } + +func TestNotaryDeregisterThenRegister(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDeposit + _, _, smc, _ := deploySMCContract(backend, mainKey) + + // Notary 0 registers + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != true { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + } + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + // Notary 0 deregisters + txOpts = bind.NewKeyedTransactor(mainKey) + _, err := smc.DeregisterNotary(txOpts) + if err != nil { + t.Fatalf("Failed to deregister notary: %v", err) + } + backend.Commit() + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + } + + // Notary 0 re-registers again + smc.RegisterNotary(txOpts) + backend.Commit() + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + } +} + +func TestNotaryRelease(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDeposit + _, _, smc, _ := deploySMCContract(backend, mainKey) + + // Notary 0 registers + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != true { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + } + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + // Fast forward 10 blocks + for i := 0; i < 10; i++ { + backend.Commit() + } + + // Notary 0 deregisters + txOpts = bind.NewKeyedTransactor(mainKey) + _, err := smc.DeregisterNotary(txOpts) + if err != nil { + t.Fatalf("Failed to deregister notary: %v", err) + } + backend.Commit() + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + } + + // Fast forward until lockup ends + for i := 0; i < int(sharding.CollatorLockupLength*sharding.PeriodLength+1); i++ { + backend.Commit() + } + + // Notary 0 releases + _, err = smc.ReleaseNotary(txOpts) + if err != nil { + t.Fatalf("Failed to release notary: %v", err) + } + backend.Commit() + + notary, err = smc.NotaryRegistry(&bind.CallOpts{}, addr) + if err != nil { + t.Fatalf("Can't get notary registry info: %v", err) + } + + if notary.Deposited != false { + t.Fatalf("Notary deposit flag should be false after released") + } + + balance, err := backend.BalanceAt(ctx, addr, nil) + + if balance.Cmp(notaryDeposit) < 0 { + t.Fatalf("Notary did not receive deposit after lock up ends") + } +} + +func TestNotaryInstantRelease(t *testing.T) { + addr := crypto.PubkeyToAddress(mainKey.PublicKey) + backend := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: accountBalance2000Eth}}) + txOpts := bind.NewKeyedTransactor(mainKey) + txOpts.Value = notaryDeposit + _, _, smc, _ := deploySMCContract(backend, mainKey) + + // Notary 0 registers + smc.RegisterNotary(txOpts) + backend.Commit() + + notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + + if notary.Deposited != true { + t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + } + + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + } + + // Fast forward 10 blocks + for i := 0; i < 10; i++ { + backend.Commit() + } + + // Notary 0 deregisters + txOpts = bind.NewKeyedTransactor(mainKey) + _, err := smc.DeregisterNotary(txOpts) + if err != nil { + t.Fatalf("Failed to deregister notary: %v", err) + } + backend.Commit() + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(0)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + } + + + // Notary 0 releases before lockup ends + _, err = smc.ReleaseNotary(txOpts) + backend.Commit() + + notary, err = smc.NotaryRegistry(&bind.CallOpts{}, addr) + if err != nil { + t.Fatalf("Can't get notary registry info: %v", err) + } + + if notary.Deposited != true { + t.Fatalf("Notary deposit flag should be true before released") + } + + balance, err := backend.BalanceAt(ctx, addr, nil) + + if balance.Cmp(notaryDeposit) > 0 { + t.Fatalf("Notary received deposit before lockup ends") + } +} \ No newline at end of file From f32a80a911965c9fd1506d5e393a424677ef08fc Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Mon, 23 Apr 2018 22:02:37 -0700 Subject: [PATCH 18/30] sharding: added tests for sampling committees Former-commit-id: abdaf09b36f79ea6dc90d2a1d6390b20fb1f2420 [formerly cd0aac8794f2c51e19bd839c0c04bdf4103731a4] Former-commit-id: 9a53826157411039ec2fad9adefd8623147b6725 --- sharding/contracts/sharding_manager.sol | 14 +- sharding/contracts/sharding_manager_test.go | 148 +++++++++++++++++++- 2 files changed, 149 insertions(+), 13 deletions(-) diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 5d976ac99..c39037064 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -74,8 +74,8 @@ contract SMC { /// Checks if a notary with given shard id and period has been chosen as /// a committee member to vote for header added on to the main chain - function isNotaryInCommittee(uint shardId, uint period) public view returns(bool) { - uint currentPeriod = block.number / PERIOD_LENGTH; + function getNotaryInCommittee(uint shardId, uint _index) public view returns(address) { + uint period = block.number / PERIOD_LENGTH; // Determine notary pool length based on notary sample size uint sampleSize; @@ -87,14 +87,9 @@ contract SMC { // Get the most recent block number before the period started uint latestBlock = period * PERIOD_LENGTH - 1; + uint index = uint(keccak256(block.blockhash(latestBlock), _index, shardId)) % sampleSize; - for (uint i = 0; i < QUORUM_SIZE; i++) { - uint index = uint(keccak256(block.blockhash(latestBlock), index)) % sampleSize; - if (notaryPool[index] == msg.sender) { - return true; - } - } - return false; + return notaryPool[index]; } /// Registers notary to notatery registry, locks in the notary deposit, @@ -148,6 +143,7 @@ contract SMC { notaryRegistry[notaryAddress].deregisteredPeriod = deregisteredPeriod; stackPush(index); + delete notaryPool[index]; --notaryPoolLength; emit NotaryDeregistered(notaryAddress, index, deregisteredPeriod); return true; diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 4848941e4..9dd735474 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -49,7 +49,6 @@ func TestContractCreation(t *testing.T) { } } -// Test register notary func TestNotaryRegister(t *testing.T) { const notaryCount = 3 var notaryPoolAddr [notaryCount]common.Address @@ -327,7 +326,7 @@ func TestNotaryRelease(t *testing.T) { } // Fast forward until lockup ends - for i := 0; i < int(sharding.CollatorLockupLength*sharding.PeriodLength+1); i++ { + for i := 0; i < int(sharding.NotaryLockupLength*sharding.PeriodLength+1); i++ { backend.Commit() } @@ -394,7 +393,6 @@ func TestNotaryInstantRelease(t *testing.T) { t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } - // Notary 0 releases before lockup ends _, err = smc.ReleaseNotary(txOpts) backend.Commit() @@ -413,4 +411,146 @@ func TestNotaryInstantRelease(t *testing.T) { if balance.Cmp(notaryDeposit) > 0 { t.Fatalf("Notary received deposit before lockup ends") } -} \ No newline at end of file +} + +func TestCommitteeListsAreDifferent(t *testing.T) { + const notaryCount = 1000 + var notaryPoolAddr [notaryCount]common.Address + var notaryPoolPrivKeys [notaryCount]*ecdsa.PrivateKey + var txOpts [notaryCount]*bind.TransactOpts + genesis := make(core.GenesisAlloc) + + for i := 0; i < notaryCount; i++ { + key, _ := crypto.GenerateKey() + notaryPoolPrivKeys[i] = key + notaryPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) + txOpts[i] = bind.NewKeyedTransactor(key) + txOpts[i].Value = notaryDeposit + genesis[notaryPoolAddr[i]] = core.GenesisAccount{ + Balance: accountBalance2000Eth, + } + } + + backend := backends.NewSimulatedBackend(genesis) + _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) + + // register 1000 notaries to SMC + for i := 0; i < notaryCount; i++ { + smc.RegisterNotary(txOpts[i]) + backend.Commit() + } + + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(1000)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 1000, Got: %v", numNotaries) + } + + // get a list of sampled notaries from shard 0 + var shard0CommitteeList []string + for i := 0; i < int(sharding.NotaryCommitSize); i++ { + addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(int64(i))) + shard0CommitteeList = append(shard0CommitteeList, addr.String()) + } + + // get a list of sampled notaries from shard 1, verify it's not identical to shard 0 + for i := 0; i < int(sharding.NotaryCommitSize); i++ { + addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(1), big.NewInt(int64(i))) + if shard0CommitteeList[i] == addr.String() { + t.Log(i) + t.Fatalf("Shard 0 committee list is identical to shard 1's committee list") + } + } +} + +func TestGetCommitteeWithNonMember(t *testing.T) { + const notaryCount = 11 + var notaryPoolAddr [notaryCount]common.Address + var notaryPoolPrivKeys [notaryCount]*ecdsa.PrivateKey + var txOpts [notaryCount]*bind.TransactOpts + genesis := make(core.GenesisAlloc) + + for i := 0; i < notaryCount; i++ { + key, _ := crypto.GenerateKey() + notaryPoolPrivKeys[i] = key + notaryPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) + txOpts[i] = bind.NewKeyedTransactor(key) + txOpts[i].Value = notaryDeposit + genesis[notaryPoolAddr[i]] = core.GenesisAccount{ + Balance: accountBalance2000Eth, + } + } + + backend := backends.NewSimulatedBackend(genesis) + _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) + + // registers 10 notaries to SMC, leave 1 address free + for i := 0; i < 10; i++ { + smc.RegisterNotary(txOpts[i]) + backend.Commit() + } + + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(10)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 135, Got: %v", numNotaries) + } + + // verify the free address can't be sampled from the committee list + for i := 0; i < 10; i++ { + addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(int64(i))) + if notaryPoolAddr[10].String() == addr.String() { + t.Fatalf("Account %s is not a notary", notaryPoolAddr[10].String()) + } + } + +} + +func TestGetCommitteeAfterDeregisters(t *testing.T) { + const notaryCount = 10 + var notaryPoolAddr [notaryCount]common.Address + var notaryPoolPrivKeys [notaryCount]*ecdsa.PrivateKey + var txOpts [notaryCount]*bind.TransactOpts + genesis := make(core.GenesisAlloc) + + for i := 0; i < notaryCount; i++ { + key, _ := crypto.GenerateKey() + notaryPoolPrivKeys[i] = key + notaryPoolAddr[i] = crypto.PubkeyToAddress(key.PublicKey) + txOpts[i] = bind.NewKeyedTransactor(key) + txOpts[i].Value = notaryDeposit + genesis[notaryPoolAddr[i]] = core.GenesisAccount{ + Balance: accountBalance2000Eth, + } + } + + backend := backends.NewSimulatedBackend(genesis) + _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) + + // register 10 notaries to SMC + for i := 0; i < 10; i++ { + smc.RegisterNotary(txOpts[i]) + backend.Commit() + } + + numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(10)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 10, Got: %v", numNotaries) + } + + // deregister notary 0 from SMC + txOpts[0].Value = big.NewInt(0) + smc.DeregisterNotary(txOpts[0]) + backend.Commit() + + numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) + if numNotaries.Cmp(big.NewInt(9)) != 0 { + t.Fatalf("Incorrect count from notary pool. Want: 9, Got: %v", numNotaries) + } + + // verify degistered notary 0 can't be sampled + for i := 0; i < 10; i++ { + addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(int64(i))) + if notaryPoolAddr[0].String() == addr.String() { + t.Fatalf("Account %s is not a notary", notaryPoolAddr[0].String()) + } + } +} From b923b9e101a4de2a43adb209c0fcb9deeeb6c654 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Tue, 24 Apr 2018 08:47:08 -0700 Subject: [PATCH 19/30] sharding: feedback changes Former-commit-id: 3251e6a3a13984b154dfb82ffae68ec214177829 [formerly 0bc330ae3445a0d88d014afa412dd4e21bdb5208] Former-commit-id: 3c3938127ccc1f56ced09496038fa0d72ed32ae7 --- sharding/contracts/sharding_manager.go | 632 +++++++++----------- sharding/contracts/sharding_manager.sol | 3 +- sharding/contracts/sharding_manager_test.go | 4 + 3 files changed, 275 insertions(+), 364 deletions(-) diff --git a/sharding/contracts/sharding_manager.go b/sharding/contracts/sharding_manager.go index c92a28435..016dab114 100644 --- a/sharding/contracts/sharding_manager.go +++ b/sharding/contracts/sharding_manager.go @@ -16,10 +16,10 @@ import ( ) // SMCABI is the input ABI used to generate the binding from. -const SMCABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"int256\"},{\"name\":\"_expectedPeriodNumber\",\"type\":\"uint256\"},{\"name\":\"_periodStartPrevHash\",\"type\":\"bytes32\"},{\"name\":\"_parentHash\",\"type\":\"bytes32\"},{\"name\":\"_transactionRoot\",\"type\":\"bytes32\"},{\"name\":\"_coinbase\",\"type\":\"address\"},{\"name\":\"_stateRoot\",\"type\":\"bytes32\"},{\"name\":\"_receiptRoot\",\"type\":\"bytes32\"},{\"name\":\"_number\",\"type\":\"int256\"}],\"name\":\"addHeader\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"shardCount\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"numCollators\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiptId\",\"type\":\"int256\"},{\"name\":\"_txGasprice\",\"type\":\"uint256\"}],\"name\":\"updateGasPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_shardId\",\"type\":\"int256\"},{\"name\":\"_txStartgas\",\"type\":\"uint256\"},{\"name\":\"_txGasprice\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes12\"}],\"name\":\"txToShard\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"periodHead\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"int256\"},{\"name\":\"_period\",\"type\":\"uint256\"}],\"name\":\"getEligibleCollator\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_collatorIndex\",\"type\":\"int256\"}],\"name\":\"withdraw\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getCollationGasLimit\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"collators\",\"outputs\":[{\"name\":\"deposit\",\"type\":\"uint256\"},{\"name\":\"addr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationHeaders\",\"outputs\":[{\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"name\":\"score\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"isCollatorDeposited\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deposit\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"receipts\",\"outputs\":[{\"name\":\"shardId\",\"type\":\"int256\"},{\"name\":\"txStartgas\",\"type\":\"uint256\"},{\"name\":\"txGasprice\",\"type\":\"uint256\"},{\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes32\"},{\"name\":\"sender\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"shardId\",\"type\":\"int256\"},{\"indexed\":false,\"name\":\"receiptId\",\"type\":\"int256\"}],\"name\":\"TxToShard\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"shardId\",\"type\":\"int256\"},{\"indexed\":false,\"name\":\"expectedPeriodNumber\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"periodStartPrevHash\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"transactionRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"coinbase\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"stateRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"receiptRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"number\",\"type\":\"int256\"},{\"indexed\":false,\"name\":\"isNewHead\",\"type\":\"bool\"},{\"indexed\":false,\"name\":\"score\",\"type\":\"int256\"}],\"name\":\"CollationAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"collator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"index\",\"type\":\"int256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"index\",\"type\":\"int256\"}],\"name\":\"Withdraw\",\"type\":\"event\"}]" +const SMCABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationTrees\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deregisterNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"periodHead\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"registerNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"notaryRegistry\",\"outputs\":[{\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"},{\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"name\":\"deposited\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"releaseNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"notaryPool\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"getNotaryInCommittee\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"uint256\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"addHeader\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"computeHeaderHash\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationHeaders\",\"outputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"notaryPoolLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"shardId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"period\",\"type\":\"int128\"},{\"indexed\":false,\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"HeaderAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryRegistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"}],\"name\":\"NotaryDeregistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryReleased\",\"type\":\"event\"}]" // SMCBin is the compiled bytecode used for deploying new contracts. -const SMCBin = `0x6060604052341561000f57600080fd5b610bcd8061001e6000396000f3006060604052600436106100cf5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630341518d81146100d457806304e9c77a146101205780630908fb31146101455780632213138914610158578063372a9e2a14610166578063584475db146101905780636115a1c3146101a65780637e62eab8146101db578063934586ec146101f35780639c23c6ab14610206578063b9d8ef961461023d578063ccb180e91461026e578063d0e30db01461028d578063d19ca56814610295575b600080fd5b34156100df57600080fd5b61010c600435602435604435606435608435600160a060020a0360a4351660c43560e435610104356102f4565b604051901515815260200160405180910390f35b341561012b57600080fd5b6101336105da565b60405190815260200160405180910390f35b341561015057600080fd5b6101336105df565b61010c6004356024356105e5565b610133600160a060020a0360043516602435604435606435600160a060020a03196084351661062a565b341561019b57600080fd5b61013360043561074d565b34156101b157600080fd5b6101bf60043560243561075f565b604051600160a060020a03909116815260200160405180910390f35b34156101e657600080fd5b6101f16004356107ed565b005b34156101fe57600080fd5b6101336108f0565b341561021157600080fd5b61021c6004356108f8565b604051918252600160a060020a031660208201526040908101905180910390f35b341561024857600080fd5b61025660043560243561091a565b60405191825260208201526040908101905180910390f35b341561027957600080fd5b61010c600160a060020a036004351661093b565b610133610950565b34156102a057600080fd5b6102ab600435610a75565b604051968752602087019590955260408087019490945260608601929092526080850152600160a060020a0390811660a085015290911660c083015260e0909101905180910390f35b60006102fe610b7a565b60008b1215801561030f575060648b125b151561031a57600080fd5b600543101561032857600080fd5b600543048a1461033757600080fd5b60001960058b020140891461034b57600080fd5b8a8a8a8a8a600160a060020a038b168a8a8a60405198895260208901979097526040808901969096526060880194909452608087019290925260a086015260c085015260e08401526101008301919091526101209091019051908190039020815260008b81526001602052604081209082518152602081019190915260400160002060010154156103d857fe5b87156104005760008b81526001602081815260408084208c8552909152822001541361040057fe5b60008b8152600960205260409020548a901261041857fe5b6104258b6005430461075f565b600160a060020a03166040820190815251600160a060020a0316151561044a57600080fd5b8060400151600160a060020a031633600160a060020a031614151561046e57600080fd5b60008b81526001602081815260408084208c855282529092208101540190820190815251831461049d57600080fd5b60408051908101604052888152602080820190830151905260008c81526001602052604081209083518152602081019190915260400160002081518155602082015160019182015560008d81526009602090815260408083208f9055838252808320600383528184205484528252909120909101549150820151131561053657805160008c815260036020526040902055600160608201525b8a7f788a01fdbeb989d24e706cdd2993ca4213400e7b5fa631819b2acfe8ebad41358b8b8b8b8b8b8b8b8a606001518b60200151604051998a5260208a01989098526040808a01979097526060890195909552600160a060020a03909316608088015260a087019190915260c086015260e08501521515610100840152610120830191909152610140909101905180910390a25060019a9950505050505050505050565b606481565b60045481565b60008281526002602052604081206005015433600160a060020a0390811691161461060f57600080fd5b50600091825260026020819052604090922090910155600190565b60008060e060405190810160409081528782526020808301889052818301879052346060840152600160a060020a031986166080840152600160a060020a0333811660a08501528a1660c08401526005546000908152600290915220815181556020820151816001015560408201518160020155606082015181600301556080820151600482015560a0820151600582018054600160a060020a031916600160a060020a039290921691909117905560c08201516006919091018054600160a060020a031916600160a060020a039283161790556005805460018101909155925087915088167ffc322e0c42ee41e0d74b940ceeee9cd5971acdd6ace8ff8010ee7134c31d9ea58360405190815260200160405180910390a39695505050505050565b60096020526000908152604090205481565b6000600482101561076f57600080fd5b4360031983016005021061078257600080fd5b6004546000901361079257600080fd5b60008061079d610abf565b600319850160050240866040519182526020820152604090810190519081900390208115156107c857fe5b068152602081019190915260400160002060010154600160a060020a03169392505050565b60008181526020819052604090206001015433600160a060020a0390811691161461081757600080fd5b6000818152602081905260409081902060018101549054600160a060020a039091169181156108fc02919051600060405180830381858888f19350505050151561086057600080fd5b600081815260208181526040808320600181018054600160a060020a0316855260088452918420805460ff19169055848452918390529190558054600160a060020a03191690556108b081610b1d565b600480546000190190557fe13f360aa18d414ccdb598da6c447faa89d0477ffc7549dab5678fca76910b8c8160405190815260200160405180910390a150565b629896805b90565b60006020819052908152604090208054600190910154600160a060020a031682565b60016020818152600093845260408085209091529183529120805491015482565b60086020526000908152604090205460ff1681565b600160a060020a033316600090815260086020526040812054819060ff161561097857600080fd5b34683635c9adc5dea000001461098d57600080fd5b610995610b3c565b15156109aa576109a3610b43565b90506109af565b506004545b604080519081016040908152348252600160a060020a0333166020808401919091526000848152908190522081518155602082015160019182018054600160a060020a031916600160a060020a0392831617905560048054830190553390811660009081526008602052604090819020805460ff19169093179092557fd8a6d38df847dcba70dfdeb4948fb1457d61a81d132801f40dc9c00d52dfd478925090839051600160a060020a03909216825260208201526040908101905180910390a1919050565b60026020819052600091825260409091208054600182015492820154600383015460048401546005850154600690950154939594929391929091600160a060020a03918216911687565b600754600454600091829101815b610400811215610b1257818112610ae357610b12565b600081815260208190526040902060010154600160a060020a031615610b0a576001830192505b600101610acd565b505060075401919050565b6007805460009081526006602052604090209190915580546001019055565b6007541590565b6000610b4d610b3c565b15610b5b57506000196108f5565b5060078054600019019081905560009081526006602052604090205490565b608060405190810160409081526000808352602083018190529082018190526060820152905600a165627a7a7230582035a29e8d01caba5d2aa31486898ecf0836674ef0786dc2e492f78b684f28ccf30029` +const SMCBin = `0x608060405234801561001057600080fd5b50610921806100206000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166303dde97781146100be57806358377bd1146100eb578063584475db1461011457806368e9513e1461012c5780636bdd3271146101345780639910851d14610175578063a81f45101461018a578063b09f427e146101be578063b8bc055f146101d9578063b9505ea414610203578063b9d8ef9614610230578063f6f67d361461027a575b600080fd5b3480156100ca57600080fd5b506100d960043560243561028f565b60408051918252519081900360200190f35b3480156100f757600080fd5b506101006102ac565b604080519115158252519081900360200190f35b34801561012057600080fd5b506100d96004356103df565b6101006103f1565b34801561014057600080fd5b50610155600160a060020a03600435166105af565b604080519384526020840192909252151582820152519081900360600190f35b34801561018157600080fd5b506101006105d2565b34801561019657600080fd5b506101a2600435610705565b60408051600160a060020a039092168252519081900360200190f35b3480156101ca57600080fd5b506101a260043560243561072d565b3480156101e557600080fd5b50610100600435602435604435600160a060020a03606435166107bb565b34801561020f57600080fd5b506100d9600435602435604435606435600160a060020a03608435166107c5565b34801561023c57600080fd5b5061024b6004356024356107d0565b60408051948552602085019390935283830191909152600160a060020a03166060830152519081900360800190f35b34801561028657600080fd5b506100d961080a565b600260209081526000928352604080842090915290825290205481565b33600160a060020a0381166000908152600160208190526040822090810154600290910154919291839060ff1615156102e457600080fd5b82600160a060020a03166000838154811015156102fd57fe5b600091825260209091200154600160a060020a03161461031c57600080fd5b610324610810565b5050600160a060020a0382166000908152600160205260409020600543049081905561034f8261083f565b600080548390811061035d57fe5b600091825260209182902001805473ffffffffffffffffffffffffffffffffffffffff191690556005805460001901905560408051600160a060020a0386168152918201849052818101839052517f90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a759181900360600190a16001935050505090565b600b6020526000908152604090205481565b33600160a060020a038116600090815260016020526040812060020154909190829060ff161561042057600080fd5b34683635c9adc5dea000001461043557600080fd5b61043d610810565b506104466108b0565b156104a95750600554600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0384161790556104f2565b6104b16108b7565b9050816000828154811015156104c357fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a031602179055505b6005805460019081019091556040805160608101825260008082526020808301868152838501868152600160a060020a0389168452918690529390912091518255915192810192909255516002909101805460ff1916911515919091179055600954811061056257600181016009555b60408051600160a060020a03841681526020810183905281517fa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7929181900390910190a160019250505090565b600160208190526000918252604090912080549181015460029091015460ff1683565b33600160a060020a0381166000908152600160208190526040822080820154600290910154929392909160ff90911615151461060d57600080fd5b600160a060020a038216600090815260016020526040902054151561063157600080fd5b600160a060020a038216600090815260016020526040902054613f0001600543041161065c57600080fd5b600160a060020a03821660008181526001602081905260408083208381559182018390556002909101805460ff1916905551683635c9adc5dea000009082818181858883f193505050501580156106b7573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517faee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680929181900390910190a160019250505090565b600080548290811061071357fe5b600091825260209091200154600160a060020a0316905081565b600080808080600543049350600a5484111561074d576009549250610753565b60085492505b60408051600019600587020180408252602082018990528183018a90529151908190036060019020909250839081151561078957fe5b06905060008181548110151561079b57fe5b600091825260209091200154600160a060020a0316979650505050505050565b6000949350505050565b600095945050505050565b60036020818152600093845260408085209091529183529120805460018201546002830154929093015490929190600160a060020a031684565b60055481565b600a54600090600543049081101561082b576000915061083b565b600954600855600a819055600191505b5090565b600754600654141561088557600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f018190556108a4565b80600660075481548110151561089757fe5b6000918252602090912001555b50600780546001019055565b6007541590565b600060016007541115156108ca57600080fd5b6007805460001901908190556006805490919081106108e557fe5b90600052602060002001549050905600a165627a7a72305820f09036677376fe46add7ec634264b1b42a1568f2d25123be3958f3625d5500da0029` // DeploySMC deploys a new Ethereum contract, binding an instance of SMC to it. func DeploySMC(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *SMC, error) { @@ -178,14 +178,18 @@ func (_SMC *SMCTransactorRaw) Transact(opts *bind.TransactOpts, method string, p // CollationHeaders is a free data retrieval call binding the contract method 0xb9d8ef96. // -// Solidity: function collationHeaders( int256, bytes32) constant returns(parentHash bytes32, score int256) +// Solidity: function collationHeaders( int256, bytes32) constant returns(shardId uint256, chunkRoot bytes32, period uint256, proposerAddress address) func (_SMC *SMCCaller) CollationHeaders(opts *bind.CallOpts, arg0 *big.Int, arg1 [32]byte) (struct { - ParentHash [32]byte - Score *big.Int + ShardId *big.Int + ChunkRoot [32]byte + Period *big.Int + ProposerAddress common.Address }, error) { ret := new(struct { - ParentHash [32]byte - Score *big.Int + ShardId *big.Int + ChunkRoot [32]byte + Period *big.Int + ProposerAddress common.Address }) out := ret err := _SMC.contract.Call(opts, out, "collationHeaders", arg0, arg1) @@ -194,162 +198,170 @@ func (_SMC *SMCCaller) CollationHeaders(opts *bind.CallOpts, arg0 *big.Int, arg1 // CollationHeaders is a free data retrieval call binding the contract method 0xb9d8ef96. // -// Solidity: function collationHeaders( int256, bytes32) constant returns(parentHash bytes32, score int256) +// Solidity: function collationHeaders( int256, bytes32) constant returns(shardId uint256, chunkRoot bytes32, period uint256, proposerAddress address) func (_SMC *SMCSession) CollationHeaders(arg0 *big.Int, arg1 [32]byte) (struct { - ParentHash [32]byte - Score *big.Int + ShardId *big.Int + ChunkRoot [32]byte + Period *big.Int + ProposerAddress common.Address }, error) { return _SMC.Contract.CollationHeaders(&_SMC.CallOpts, arg0, arg1) } // CollationHeaders is a free data retrieval call binding the contract method 0xb9d8ef96. // -// Solidity: function collationHeaders( int256, bytes32) constant returns(parentHash bytes32, score int256) +// Solidity: function collationHeaders( int256, bytes32) constant returns(shardId uint256, chunkRoot bytes32, period uint256, proposerAddress address) func (_SMC *SMCCallerSession) CollationHeaders(arg0 *big.Int, arg1 [32]byte) (struct { - ParentHash [32]byte - Score *big.Int + ShardId *big.Int + ChunkRoot [32]byte + Period *big.Int + ProposerAddress common.Address }, error) { return _SMC.Contract.CollationHeaders(&_SMC.CallOpts, arg0, arg1) } -// Collators is a free data retrieval call binding the contract method 0x9c23c6ab. +// CollationTrees is a free data retrieval call binding the contract method 0x03dde977. // -// Solidity: function collators( int256) constant returns(deposit uint256, addr address) -func (_SMC *SMCCaller) Collators(opts *bind.CallOpts, arg0 *big.Int) (struct { - Deposit *big.Int - Addr common.Address -}, error) { - ret := new(struct { - Deposit *big.Int - Addr common.Address - }) - out := ret - err := _SMC.contract.Call(opts, out, "collators", arg0) - return *ret, err -} - -// Collators is a free data retrieval call binding the contract method 0x9c23c6ab. -// -// Solidity: function collators( int256) constant returns(deposit uint256, addr address) -func (_SMC *SMCSession) Collators(arg0 *big.Int) (struct { - Deposit *big.Int - Addr common.Address -}, error) { - return _SMC.Contract.Collators(&_SMC.CallOpts, arg0) -} - -// Collators is a free data retrieval call binding the contract method 0x9c23c6ab. -// -// Solidity: function collators( int256) constant returns(deposit uint256, addr address) -func (_SMC *SMCCallerSession) Collators(arg0 *big.Int) (struct { - Deposit *big.Int - Addr common.Address -}, error) { - return _SMC.Contract.Collators(&_SMC.CallOpts, arg0) -} - -// GetCollationGasLimit is a free data retrieval call binding the contract method 0x934586ec. -// -// Solidity: function getCollationGasLimit() constant returns(uint256) -func (_SMC *SMCCaller) GetCollationGasLimit(opts *bind.CallOpts) (*big.Int, error) { +// Solidity: function collationTrees( uint256, bytes32) constant returns(bytes32) +func (_SMC *SMCCaller) CollationTrees(opts *bind.CallOpts, arg0 *big.Int, arg1 [32]byte) ([32]byte, error) { var ( - ret0 = new(*big.Int) + ret0 = new([32]byte) ) out := ret0 - err := _SMC.contract.Call(opts, out, "getCollationGasLimit") + err := _SMC.contract.Call(opts, out, "collationTrees", arg0, arg1) return *ret0, err } -// GetCollationGasLimit is a free data retrieval call binding the contract method 0x934586ec. +// CollationTrees is a free data retrieval call binding the contract method 0x03dde977. // -// Solidity: function getCollationGasLimit() constant returns(uint256) -func (_SMC *SMCSession) GetCollationGasLimit() (*big.Int, error) { - return _SMC.Contract.GetCollationGasLimit(&_SMC.CallOpts) +// Solidity: function collationTrees( uint256, bytes32) constant returns(bytes32) +func (_SMC *SMCSession) CollationTrees(arg0 *big.Int, arg1 [32]byte) ([32]byte, error) { + return _SMC.Contract.CollationTrees(&_SMC.CallOpts, arg0, arg1) } -// GetCollationGasLimit is a free data retrieval call binding the contract method 0x934586ec. +// CollationTrees is a free data retrieval call binding the contract method 0x03dde977. // -// Solidity: function getCollationGasLimit() constant returns(uint256) -func (_SMC *SMCCallerSession) GetCollationGasLimit() (*big.Int, error) { - return _SMC.Contract.GetCollationGasLimit(&_SMC.CallOpts) +// Solidity: function collationTrees( uint256, bytes32) constant returns(bytes32) +func (_SMC *SMCCallerSession) CollationTrees(arg0 *big.Int, arg1 [32]byte) ([32]byte, error) { + return _SMC.Contract.CollationTrees(&_SMC.CallOpts, arg0, arg1) } -// GetEligibleCollator is a free data retrieval call binding the contract method 0x6115a1c3. +// GetNotaryInCommittee is a free data retrieval call binding the contract method 0xb09f427e. // -// Solidity: function getEligibleCollator(_shardId int256, _period uint256) constant returns(address) -func (_SMC *SMCCaller) GetEligibleCollator(opts *bind.CallOpts, _shardId *big.Int, _period *big.Int) (common.Address, error) { +// Solidity: function getNotaryInCommittee(shardId uint256, _index uint256) constant returns(address) +func (_SMC *SMCCaller) GetNotaryInCommittee(opts *bind.CallOpts, shardId *big.Int, _index *big.Int) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 - err := _SMC.contract.Call(opts, out, "getEligibleCollator", _shardId, _period) + err := _SMC.contract.Call(opts, out, "getNotaryInCommittee", shardId, _index) return *ret0, err } -// GetEligibleCollator is a free data retrieval call binding the contract method 0x6115a1c3. +// GetNotaryInCommittee is a free data retrieval call binding the contract method 0xb09f427e. // -// Solidity: function getEligibleCollator(_shardId int256, _period uint256) constant returns(address) -func (_SMC *SMCSession) GetEligibleCollator(_shardId *big.Int, _period *big.Int) (common.Address, error) { - return _SMC.Contract.GetEligibleCollator(&_SMC.CallOpts, _shardId, _period) +// Solidity: function getNotaryInCommittee(shardId uint256, _index uint256) constant returns(address) +func (_SMC *SMCSession) GetNotaryInCommittee(shardId *big.Int, _index *big.Int) (common.Address, error) { + return _SMC.Contract.GetNotaryInCommittee(&_SMC.CallOpts, shardId, _index) } -// GetEligibleCollator is a free data retrieval call binding the contract method 0x6115a1c3. +// GetNotaryInCommittee is a free data retrieval call binding the contract method 0xb09f427e. // -// Solidity: function getEligibleCollator(_shardId int256, _period uint256) constant returns(address) -func (_SMC *SMCCallerSession) GetEligibleCollator(_shardId *big.Int, _period *big.Int) (common.Address, error) { - return _SMC.Contract.GetEligibleCollator(&_SMC.CallOpts, _shardId, _period) +// Solidity: function getNotaryInCommittee(shardId uint256, _index uint256) constant returns(address) +func (_SMC *SMCCallerSession) GetNotaryInCommittee(shardId *big.Int, _index *big.Int) (common.Address, error) { + return _SMC.Contract.GetNotaryInCommittee(&_SMC.CallOpts, shardId, _index) } -// IsCollatorDeposited is a free data retrieval call binding the contract method 0xccb180e9. +// NotaryPool is a free data retrieval call binding the contract method 0xa81f4510. // -// Solidity: function isCollatorDeposited( address) constant returns(bool) -func (_SMC *SMCCaller) IsCollatorDeposited(opts *bind.CallOpts, arg0 common.Address) (bool, error) { +// Solidity: function notaryPool( uint256) constant returns(address) +func (_SMC *SMCCaller) NotaryPool(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) { var ( - ret0 = new(bool) + ret0 = new(common.Address) ) out := ret0 - err := _SMC.contract.Call(opts, out, "isCollatorDeposited", arg0) + err := _SMC.contract.Call(opts, out, "notaryPool", arg0) return *ret0, err } -// IsCollatorDeposited is a free data retrieval call binding the contract method 0xccb180e9. +// NotaryPool is a free data retrieval call binding the contract method 0xa81f4510. // -// Solidity: function isCollatorDeposited( address) constant returns(bool) -func (_SMC *SMCSession) IsCollatorDeposited(arg0 common.Address) (bool, error) { - return _SMC.Contract.IsCollatorDeposited(&_SMC.CallOpts, arg0) +// Solidity: function notaryPool( uint256) constant returns(address) +func (_SMC *SMCSession) NotaryPool(arg0 *big.Int) (common.Address, error) { + return _SMC.Contract.NotaryPool(&_SMC.CallOpts, arg0) } -// IsCollatorDeposited is a free data retrieval call binding the contract method 0xccb180e9. +// NotaryPool is a free data retrieval call binding the contract method 0xa81f4510. // -// Solidity: function isCollatorDeposited( address) constant returns(bool) -func (_SMC *SMCCallerSession) IsCollatorDeposited(arg0 common.Address) (bool, error) { - return _SMC.Contract.IsCollatorDeposited(&_SMC.CallOpts, arg0) +// Solidity: function notaryPool( uint256) constant returns(address) +func (_SMC *SMCCallerSession) NotaryPool(arg0 *big.Int) (common.Address, error) { + return _SMC.Contract.NotaryPool(&_SMC.CallOpts, arg0) } -// NumCollators is a free data retrieval call binding the contract method 0x0908fb31. +// NotaryPoolLength is a free data retrieval call binding the contract method 0xf6f67d36. // -// Solidity: function numCollators() constant returns(int256) -func (_SMC *SMCCaller) NumCollators(opts *bind.CallOpts) (*big.Int, error) { +// Solidity: function notaryPoolLength() constant returns(uint256) +func (_SMC *SMCCaller) NotaryPoolLength(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 - err := _SMC.contract.Call(opts, out, "numCollators") + err := _SMC.contract.Call(opts, out, "notaryPoolLength") return *ret0, err } -// NumCollators is a free data retrieval call binding the contract method 0x0908fb31. +// NotaryPoolLength is a free data retrieval call binding the contract method 0xf6f67d36. // -// Solidity: function numCollators() constant returns(int256) -func (_SMC *SMCSession) NumCollators() (*big.Int, error) { - return _SMC.Contract.NumCollators(&_SMC.CallOpts) +// Solidity: function notaryPoolLength() constant returns(uint256) +func (_SMC *SMCSession) NotaryPoolLength() (*big.Int, error) { + return _SMC.Contract.NotaryPoolLength(&_SMC.CallOpts) } -// NumCollators is a free data retrieval call binding the contract method 0x0908fb31. +// NotaryPoolLength is a free data retrieval call binding the contract method 0xf6f67d36. // -// Solidity: function numCollators() constant returns(int256) -func (_SMC *SMCCallerSession) NumCollators() (*big.Int, error) { - return _SMC.Contract.NumCollators(&_SMC.CallOpts) +// Solidity: function notaryPoolLength() constant returns(uint256) +func (_SMC *SMCCallerSession) NotaryPoolLength() (*big.Int, error) { + return _SMC.Contract.NotaryPoolLength(&_SMC.CallOpts) +} + +// NotaryRegistry is a free data retrieval call binding the contract method 0x6bdd3271. +// +// Solidity: function notaryRegistry( address) constant returns(deregisteredPeriod uint256, poolIndex uint256, deposited bool) +func (_SMC *SMCCaller) NotaryRegistry(opts *bind.CallOpts, arg0 common.Address) (struct { + DeregisteredPeriod *big.Int + PoolIndex *big.Int + Deposited bool +}, error) { + ret := new(struct { + DeregisteredPeriod *big.Int + PoolIndex *big.Int + Deposited bool + }) + out := ret + err := _SMC.contract.Call(opts, out, "notaryRegistry", arg0) + return *ret, err +} + +// NotaryRegistry is a free data retrieval call binding the contract method 0x6bdd3271. +// +// Solidity: function notaryRegistry( address) constant returns(deregisteredPeriod uint256, poolIndex uint256, deposited bool) +func (_SMC *SMCSession) NotaryRegistry(arg0 common.Address) (struct { + DeregisteredPeriod *big.Int + PoolIndex *big.Int + Deposited bool +}, error) { + return _SMC.Contract.NotaryRegistry(&_SMC.CallOpts, arg0) +} + +// NotaryRegistry is a free data retrieval call binding the contract method 0x6bdd3271. +// +// Solidity: function notaryRegistry( address) constant returns(deregisteredPeriod uint256, poolIndex uint256, deposited bool) +func (_SMC *SMCCallerSession) NotaryRegistry(arg0 common.Address) (struct { + DeregisteredPeriod *big.Int + PoolIndex *big.Int + Deposited bool +}, error) { + return _SMC.Contract.NotaryRegistry(&_SMC.CallOpts, arg0) } // PeriodHead is a free data retrieval call binding the contract method 0x584475db. @@ -378,196 +390,114 @@ func (_SMC *SMCCallerSession) PeriodHead(arg0 *big.Int) (*big.Int, error) { return _SMC.Contract.PeriodHead(&_SMC.CallOpts, arg0) } -// Receipts is a free data retrieval call binding the contract method 0xd19ca568. +// AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function receipts( int256) constant returns(shardId int256, txStartgas uint256, txGasprice uint256, value uint256, data bytes32, sender address, to address) -func (_SMC *SMCCaller) Receipts(opts *bind.CallOpts, arg0 *big.Int) (struct { - ShardId *big.Int - TxStartgas *big.Int - TxGasprice *big.Int - Value *big.Int - Data [32]byte - Sender common.Address - To common.Address -}, error) { - ret := new(struct { - ShardId *big.Int - TxStartgas *big.Int - TxGasprice *big.Int - Value *big.Int - Data [32]byte - Sender common.Address - To common.Address - }) - out := ret - err := _SMC.contract.Call(opts, out, "receipts", arg0) - return *ret, err +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +func (_SMC *SMCTransactor) AddHeader(opts *bind.TransactOpts, _shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.contract.Transact(opts, "addHeader", _shardId, period, chunkRoot, proposerAddress) } -// Receipts is a free data retrieval call binding the contract method 0xd19ca568. +// AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function receipts( int256) constant returns(shardId int256, txStartgas uint256, txGasprice uint256, value uint256, data bytes32, sender address, to address) -func (_SMC *SMCSession) Receipts(arg0 *big.Int) (struct { - ShardId *big.Int - TxStartgas *big.Int - TxGasprice *big.Int - Value *big.Int - Data [32]byte - Sender common.Address - To common.Address -}, error) { - return _SMC.Contract.Receipts(&_SMC.CallOpts, arg0) +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +func (_SMC *SMCSession) AddHeader(_shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, period, chunkRoot, proposerAddress) } -// Receipts is a free data retrieval call binding the contract method 0xd19ca568. +// AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function receipts( int256) constant returns(shardId int256, txStartgas uint256, txGasprice uint256, value uint256, data bytes32, sender address, to address) -func (_SMC *SMCCallerSession) Receipts(arg0 *big.Int) (struct { - ShardId *big.Int - TxStartgas *big.Int - TxGasprice *big.Int - Value *big.Int - Data [32]byte - Sender common.Address - To common.Address -}, error) { - return _SMC.Contract.Receipts(&_SMC.CallOpts, arg0) +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +func (_SMC *SMCTransactorSession) AddHeader(_shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, period, chunkRoot, proposerAddress) } -// ShardCount is a free data retrieval call binding the contract method 0x04e9c77a. +// ComputeHeaderHash is a paid mutator transaction binding the contract method 0xb9505ea4. // -// Solidity: function shardCount() constant returns(int256) -func (_SMC *SMCCaller) ShardCount(opts *bind.CallOpts) (*big.Int, error) { - var ( - ret0 = new(*big.Int) - ) - out := ret0 - err := _SMC.contract.Call(opts, out, "shardCount") - return *ret0, err +// Solidity: function computeHeaderHash(shardId uint256, parentHash bytes32, chunkRoot bytes32, period uint256, proposerAddress address) returns(bytes32) +func (_SMC *SMCTransactor) ComputeHeaderHash(opts *bind.TransactOpts, shardId *big.Int, parentHash [32]byte, chunkRoot [32]byte, period *big.Int, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.contract.Transact(opts, "computeHeaderHash", shardId, parentHash, chunkRoot, period, proposerAddress) } -// ShardCount is a free data retrieval call binding the contract method 0x04e9c77a. +// ComputeHeaderHash is a paid mutator transaction binding the contract method 0xb9505ea4. // -// Solidity: function shardCount() constant returns(int256) -func (_SMC *SMCSession) ShardCount() (*big.Int, error) { - return _SMC.Contract.ShardCount(&_SMC.CallOpts) +// Solidity: function computeHeaderHash(shardId uint256, parentHash bytes32, chunkRoot bytes32, period uint256, proposerAddress address) returns(bytes32) +func (_SMC *SMCSession) ComputeHeaderHash(shardId *big.Int, parentHash [32]byte, chunkRoot [32]byte, period *big.Int, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.Contract.ComputeHeaderHash(&_SMC.TransactOpts, shardId, parentHash, chunkRoot, period, proposerAddress) } -// ShardCount is a free data retrieval call binding the contract method 0x04e9c77a. +// ComputeHeaderHash is a paid mutator transaction binding the contract method 0xb9505ea4. // -// Solidity: function shardCount() constant returns(int256) -func (_SMC *SMCCallerSession) ShardCount() (*big.Int, error) { - return _SMC.Contract.ShardCount(&_SMC.CallOpts) +// Solidity: function computeHeaderHash(shardId uint256, parentHash bytes32, chunkRoot bytes32, period uint256, proposerAddress address) returns(bytes32) +func (_SMC *SMCTransactorSession) ComputeHeaderHash(shardId *big.Int, parentHash [32]byte, chunkRoot [32]byte, period *big.Int, proposerAddress common.Address) (*types.Transaction, error) { + return _SMC.Contract.ComputeHeaderHash(&_SMC.TransactOpts, shardId, parentHash, chunkRoot, period, proposerAddress) } -// AddHeader is a paid mutator transaction binding the contract method 0x0341518d. +// DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function addHeader(_shardId int256, _expectedPeriodNumber uint256, _periodStartPrevHash bytes32, _parentHash bytes32, _transactionRoot bytes32, _coinbase address, _stateRoot bytes32, _receiptRoot bytes32, _number int256) returns(bool) -func (_SMC *SMCTransactor) AddHeader(opts *bind.TransactOpts, _shardId *big.Int, _expectedPeriodNumber *big.Int, _periodStartPrevHash [32]byte, _parentHash [32]byte, _transactionRoot [32]byte, _coinbase common.Address, _stateRoot [32]byte, _receiptRoot [32]byte, _number *big.Int) (*types.Transaction, error) { - return _SMC.contract.Transact(opts, "addHeader", _shardId, _expectedPeriodNumber, _periodStartPrevHash, _parentHash, _transactionRoot, _coinbase, _stateRoot, _receiptRoot, _number) +// Solidity: function deregisterNotary() returns(bool) +func (_SMC *SMCTransactor) DeregisterNotary(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SMC.contract.Transact(opts, "deregisterNotary") } -// AddHeader is a paid mutator transaction binding the contract method 0x0341518d. +// DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function addHeader(_shardId int256, _expectedPeriodNumber uint256, _periodStartPrevHash bytes32, _parentHash bytes32, _transactionRoot bytes32, _coinbase address, _stateRoot bytes32, _receiptRoot bytes32, _number int256) returns(bool) -func (_SMC *SMCSession) AddHeader(_shardId *big.Int, _expectedPeriodNumber *big.Int, _periodStartPrevHash [32]byte, _parentHash [32]byte, _transactionRoot [32]byte, _coinbase common.Address, _stateRoot [32]byte, _receiptRoot [32]byte, _number *big.Int) (*types.Transaction, error) { - return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, _expectedPeriodNumber, _periodStartPrevHash, _parentHash, _transactionRoot, _coinbase, _stateRoot, _receiptRoot, _number) +// Solidity: function deregisterNotary() returns(bool) +func (_SMC *SMCSession) DeregisterNotary() (*types.Transaction, error) { + return _SMC.Contract.DeregisterNotary(&_SMC.TransactOpts) } -// AddHeader is a paid mutator transaction binding the contract method 0x0341518d. +// DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function addHeader(_shardId int256, _expectedPeriodNumber uint256, _periodStartPrevHash bytes32, _parentHash bytes32, _transactionRoot bytes32, _coinbase address, _stateRoot bytes32, _receiptRoot bytes32, _number int256) returns(bool) -func (_SMC *SMCTransactorSession) AddHeader(_shardId *big.Int, _expectedPeriodNumber *big.Int, _periodStartPrevHash [32]byte, _parentHash [32]byte, _transactionRoot [32]byte, _coinbase common.Address, _stateRoot [32]byte, _receiptRoot [32]byte, _number *big.Int) (*types.Transaction, error) { - return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, _expectedPeriodNumber, _periodStartPrevHash, _parentHash, _transactionRoot, _coinbase, _stateRoot, _receiptRoot, _number) +// Solidity: function deregisterNotary() returns(bool) +func (_SMC *SMCTransactorSession) DeregisterNotary() (*types.Transaction, error) { + return _SMC.Contract.DeregisterNotary(&_SMC.TransactOpts) } -// Deposit is a paid mutator transaction binding the contract method 0xd0e30db0. +// RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function deposit() returns(int256) -func (_SMC *SMCTransactor) Deposit(opts *bind.TransactOpts) (*types.Transaction, error) { - return _SMC.contract.Transact(opts, "deposit") +// Solidity: function registerNotary() returns(bool) +func (_SMC *SMCTransactor) RegisterNotary(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SMC.contract.Transact(opts, "registerNotary") } -// Deposit is a paid mutator transaction binding the contract method 0xd0e30db0. +// RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function deposit() returns(int256) -func (_SMC *SMCSession) Deposit() (*types.Transaction, error) { - return _SMC.Contract.Deposit(&_SMC.TransactOpts) +// Solidity: function registerNotary() returns(bool) +func (_SMC *SMCSession) RegisterNotary() (*types.Transaction, error) { + return _SMC.Contract.RegisterNotary(&_SMC.TransactOpts) } -// Deposit is a paid mutator transaction binding the contract method 0xd0e30db0. +// RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function deposit() returns(int256) -func (_SMC *SMCTransactorSession) Deposit() (*types.Transaction, error) { - return _SMC.Contract.Deposit(&_SMC.TransactOpts) +// Solidity: function registerNotary() returns(bool) +func (_SMC *SMCTransactorSession) RegisterNotary() (*types.Transaction, error) { + return _SMC.Contract.RegisterNotary(&_SMC.TransactOpts) } -// TxToShard is a paid mutator transaction binding the contract method 0x372a9e2a. +// ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function txToShard(_to address, _shardId int256, _txStartgas uint256, _txGasprice uint256, _data bytes12) returns(int256) -func (_SMC *SMCTransactor) TxToShard(opts *bind.TransactOpts, _to common.Address, _shardId *big.Int, _txStartgas *big.Int, _txGasprice *big.Int, _data [12]byte) (*types.Transaction, error) { - return _SMC.contract.Transact(opts, "txToShard", _to, _shardId, _txStartgas, _txGasprice, _data) +// Solidity: function releaseNotary() returns(bool) +func (_SMC *SMCTransactor) ReleaseNotary(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SMC.contract.Transact(opts, "releaseNotary") } -// TxToShard is a paid mutator transaction binding the contract method 0x372a9e2a. +// ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function txToShard(_to address, _shardId int256, _txStartgas uint256, _txGasprice uint256, _data bytes12) returns(int256) -func (_SMC *SMCSession) TxToShard(_to common.Address, _shardId *big.Int, _txStartgas *big.Int, _txGasprice *big.Int, _data [12]byte) (*types.Transaction, error) { - return _SMC.Contract.TxToShard(&_SMC.TransactOpts, _to, _shardId, _txStartgas, _txGasprice, _data) +// Solidity: function releaseNotary() returns(bool) +func (_SMC *SMCSession) ReleaseNotary() (*types.Transaction, error) { + return _SMC.Contract.ReleaseNotary(&_SMC.TransactOpts) } -// TxToShard is a paid mutator transaction binding the contract method 0x372a9e2a. +// ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function txToShard(_to address, _shardId int256, _txStartgas uint256, _txGasprice uint256, _data bytes12) returns(int256) -func (_SMC *SMCTransactorSession) TxToShard(_to common.Address, _shardId *big.Int, _txStartgas *big.Int, _txGasprice *big.Int, _data [12]byte) (*types.Transaction, error) { - return _SMC.Contract.TxToShard(&_SMC.TransactOpts, _to, _shardId, _txStartgas, _txGasprice, _data) +// Solidity: function releaseNotary() returns(bool) +func (_SMC *SMCTransactorSession) ReleaseNotary() (*types.Transaction, error) { + return _SMC.Contract.ReleaseNotary(&_SMC.TransactOpts) } -// UpdateGasPrice is a paid mutator transaction binding the contract method 0x22131389. -// -// Solidity: function updateGasPrice(_receiptId int256, _txGasprice uint256) returns(bool) -func (_SMC *SMCTransactor) UpdateGasPrice(opts *bind.TransactOpts, _receiptId *big.Int, _txGasprice *big.Int) (*types.Transaction, error) { - return _SMC.contract.Transact(opts, "updateGasPrice", _receiptId, _txGasprice) -} - -// UpdateGasPrice is a paid mutator transaction binding the contract method 0x22131389. -// -// Solidity: function updateGasPrice(_receiptId int256, _txGasprice uint256) returns(bool) -func (_SMC *SMCSession) UpdateGasPrice(_receiptId *big.Int, _txGasprice *big.Int) (*types.Transaction, error) { - return _SMC.Contract.UpdateGasPrice(&_SMC.TransactOpts, _receiptId, _txGasprice) -} - -// UpdateGasPrice is a paid mutator transaction binding the contract method 0x22131389. -// -// Solidity: function updateGasPrice(_receiptId int256, _txGasprice uint256) returns(bool) -func (_SMC *SMCTransactorSession) UpdateGasPrice(_receiptId *big.Int, _txGasprice *big.Int) (*types.Transaction, error) { - return _SMC.Contract.UpdateGasPrice(&_SMC.TransactOpts, _receiptId, _txGasprice) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x7e62eab8. -// -// Solidity: function withdraw(_collatorIndex int256) returns() -func (_SMC *SMCTransactor) Withdraw(opts *bind.TransactOpts, _collatorIndex *big.Int) (*types.Transaction, error) { - return _SMC.contract.Transact(opts, "withdraw", _collatorIndex) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x7e62eab8. -// -// Solidity: function withdraw(_collatorIndex int256) returns() -func (_SMC *SMCSession) Withdraw(_collatorIndex *big.Int) (*types.Transaction, error) { - return _SMC.Contract.Withdraw(&_SMC.TransactOpts, _collatorIndex) -} - -// Withdraw is a paid mutator transaction binding the contract method 0x7e62eab8. -// -// Solidity: function withdraw(_collatorIndex int256) returns() -func (_SMC *SMCTransactorSession) Withdraw(_collatorIndex *big.Int) (*types.Transaction, error) { - return _SMC.Contract.Withdraw(&_SMC.TransactOpts, _collatorIndex) -} - -// SMCCollationAddedIterator is returned from FilterCollationAdded and is used to iterate over the raw logs and unpacked data for CollationAdded events raised by the SMC contract. -type SMCCollationAddedIterator struct { - Event *SMCCollationAdded // Event containing the contract specifics and raw log +// SMCHeaderAddedIterator is returned from FilterHeaderAdded and is used to iterate over the raw logs and unpacked data for HeaderAdded events raised by the SMC contract. +type SMCHeaderAddedIterator struct { + Event *SMCHeaderAdded // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data @@ -581,7 +511,7 @@ type SMCCollationAddedIterator struct { // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. -func (it *SMCCollationAddedIterator) Next() bool { +func (it *SMCHeaderAddedIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false @@ -590,7 +520,7 @@ func (it *SMCCollationAddedIterator) Next() bool { if it.done { select { case log := <-it.logs: - it.Event = new(SMCCollationAdded) + it.Event = new(SMCHeaderAdded) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -605,7 +535,7 @@ func (it *SMCCollationAddedIterator) Next() bool { // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: - it.Event = new(SMCCollationAdded) + it.Event = new(SMCHeaderAdded) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -621,61 +551,54 @@ func (it *SMCCollationAddedIterator) Next() bool { } // Error returns any retrieval or parsing error occurred during filtering. -func (it *SMCCollationAddedIterator) Error() error { +func (it *SMCHeaderAddedIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. -func (it *SMCCollationAddedIterator) Close() error { +func (it *SMCHeaderAddedIterator) Close() error { it.sub.Unsubscribe() return nil } -// SMCCollationAdded represents a CollationAdded event raised by the SMC contract. -type SMCCollationAdded struct { - ShardId *big.Int - ExpectedPeriodNumber *big.Int - PeriodStartPrevHash [32]byte - ParentHash [32]byte - TransactionRoot [32]byte - Coinbase common.Address - StateRoot [32]byte - ReceiptRoot [32]byte - Number *big.Int - IsNewHead bool - Score *big.Int - Raw types.Log // Blockchain specific contextual infos +// SMCHeaderAdded represents a HeaderAdded event raised by the SMC contract. +type SMCHeaderAdded struct { + ShardId *big.Int + ChunkRoot [32]byte + Period *big.Int + ProposerAddress common.Address + Raw types.Log // Blockchain specific contextual infos } -// FilterCollationAdded is a free log retrieval operation binding the contract event 0x788a01fdbeb989d24e706cdd2993ca4213400e7b5fa631819b2acfe8ebad4135. +// FilterHeaderAdded is a free log retrieval operation binding the contract event 0x5585108fa6e3c23be15f85641f8d891b72782aaeca2573e7360a4519e67a2bee. // -// Solidity: event CollationAdded(shardId indexed int256, expectedPeriodNumber uint256, periodStartPrevHash bytes32, parentHash bytes32, transactionRoot bytes32, coinbase address, stateRoot bytes32, receiptRoot bytes32, number int256, isNewHead bool, score int256) -func (_SMC *SMCFilterer) FilterCollationAdded(opts *bind.FilterOpts, shardId []*big.Int) (*SMCCollationAddedIterator, error) { +// Solidity: event HeaderAdded(shardId indexed uint256, chunkRoot bytes32, period int128, proposerAddress address) +func (_SMC *SMCFilterer) FilterHeaderAdded(opts *bind.FilterOpts, shardId []*big.Int) (*SMCHeaderAddedIterator, error) { var shardIdRule []interface{} for _, shardIdItem := range shardId { shardIdRule = append(shardIdRule, shardIdItem) } - logs, sub, err := _SMC.contract.FilterLogs(opts, "CollationAdded", shardIdRule) + logs, sub, err := _SMC.contract.FilterLogs(opts, "HeaderAdded", shardIdRule) if err != nil { return nil, err } - return &SMCCollationAddedIterator{contract: _SMC.contract, event: "CollationAdded", logs: logs, sub: sub}, nil + return &SMCHeaderAddedIterator{contract: _SMC.contract, event: "HeaderAdded", logs: logs, sub: sub}, nil } -// WatchCollationAdded is a free log subscription operation binding the contract event 0x788a01fdbeb989d24e706cdd2993ca4213400e7b5fa631819b2acfe8ebad4135. +// WatchHeaderAdded is a free log subscription operation binding the contract event 0x5585108fa6e3c23be15f85641f8d891b72782aaeca2573e7360a4519e67a2bee. // -// Solidity: event CollationAdded(shardId indexed int256, expectedPeriodNumber uint256, periodStartPrevHash bytes32, parentHash bytes32, transactionRoot bytes32, coinbase address, stateRoot bytes32, receiptRoot bytes32, number int256, isNewHead bool, score int256) -func (_SMC *SMCFilterer) WatchCollationAdded(opts *bind.WatchOpts, sink chan<- *SMCCollationAdded, shardId []*big.Int) (event.Subscription, error) { +// Solidity: event HeaderAdded(shardId indexed uint256, chunkRoot bytes32, period int128, proposerAddress address) +func (_SMC *SMCFilterer) WatchHeaderAdded(opts *bind.WatchOpts, sink chan<- *SMCHeaderAdded, shardId []*big.Int) (event.Subscription, error) { var shardIdRule []interface{} for _, shardIdItem := range shardId { shardIdRule = append(shardIdRule, shardIdItem) } - logs, sub, err := _SMC.contract.WatchLogs(opts, "CollationAdded", shardIdRule) + logs, sub, err := _SMC.contract.WatchLogs(opts, "HeaderAdded", shardIdRule) if err != nil { return nil, err } @@ -685,8 +608,8 @@ func (_SMC *SMCFilterer) WatchCollationAdded(opts *bind.WatchOpts, sink chan<- * select { case log := <-logs: // New log arrived, parse the event and forward to the user - event := new(SMCCollationAdded) - if err := _SMC.contract.UnpackLog(event, "CollationAdded", log); err != nil { + event := new(SMCHeaderAdded) + if err := _SMC.contract.UnpackLog(event, "HeaderAdded", log); err != nil { return err } event.Raw = log @@ -707,9 +630,9 @@ func (_SMC *SMCFilterer) WatchCollationAdded(opts *bind.WatchOpts, sink chan<- * }), nil } -// SMCDepositIterator is returned from FilterDeposit and is used to iterate over the raw logs and unpacked data for Deposit events raised by the SMC contract. -type SMCDepositIterator struct { - Event *SMCDeposit // Event containing the contract specifics and raw log +// SMCNotaryDeregisteredIterator is returned from FilterNotaryDeregistered and is used to iterate over the raw logs and unpacked data for NotaryDeregistered events raised by the SMC contract. +type SMCNotaryDeregisteredIterator struct { + Event *SMCNotaryDeregistered // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data @@ -723,7 +646,7 @@ type SMCDepositIterator struct { // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. -func (it *SMCDepositIterator) Next() bool { +func (it *SMCNotaryDeregisteredIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false @@ -732,7 +655,7 @@ func (it *SMCDepositIterator) Next() bool { if it.done { select { case log := <-it.logs: - it.Event = new(SMCDeposit) + it.Event = new(SMCNotaryDeregistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -747,7 +670,7 @@ func (it *SMCDepositIterator) Next() bool { // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: - it.Event = new(SMCDeposit) + it.Event = new(SMCNotaryDeregistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -763,42 +686,43 @@ func (it *SMCDepositIterator) Next() bool { } // Error returns any retrieval or parsing error occurred during filtering. -func (it *SMCDepositIterator) Error() error { +func (it *SMCNotaryDeregisteredIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. -func (it *SMCDepositIterator) Close() error { +func (it *SMCNotaryDeregisteredIterator) Close() error { it.sub.Unsubscribe() return nil } -// SMCDeposit represents a Deposit event raised by the SMC contract. -type SMCDeposit struct { - Collator common.Address - Index *big.Int - Raw types.Log // Blockchain specific contextual infos +// SMCNotaryDeregistered represents a NotaryDeregistered event raised by the SMC contract. +type SMCNotaryDeregistered struct { + Notary common.Address + PoolIndex *big.Int + DeregisteredPeriod *big.Int + Raw types.Log // Blockchain specific contextual infos } -// FilterDeposit is a free log retrieval operation binding the contract event 0xd8a6d38df847dcba70dfdeb4948fb1457d61a81d132801f40dc9c00d52dfd478. +// FilterNotaryDeregistered is a free log retrieval operation binding the contract event 0x90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a75. // -// Solidity: event Deposit(collator address, index int256) -func (_SMC *SMCFilterer) FilterDeposit(opts *bind.FilterOpts) (*SMCDepositIterator, error) { +// Solidity: event NotaryDeregistered(notary address, poolIndex uint256, deregisteredPeriod uint256) +func (_SMC *SMCFilterer) FilterNotaryDeregistered(opts *bind.FilterOpts) (*SMCNotaryDeregisteredIterator, error) { - logs, sub, err := _SMC.contract.FilterLogs(opts, "Deposit") + logs, sub, err := _SMC.contract.FilterLogs(opts, "NotaryDeregistered") if err != nil { return nil, err } - return &SMCDepositIterator{contract: _SMC.contract, event: "Deposit", logs: logs, sub: sub}, nil + return &SMCNotaryDeregisteredIterator{contract: _SMC.contract, event: "NotaryDeregistered", logs: logs, sub: sub}, nil } -// WatchDeposit is a free log subscription operation binding the contract event 0xd8a6d38df847dcba70dfdeb4948fb1457d61a81d132801f40dc9c00d52dfd478. +// WatchNotaryDeregistered is a free log subscription operation binding the contract event 0x90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a75. // -// Solidity: event Deposit(collator address, index int256) -func (_SMC *SMCFilterer) WatchDeposit(opts *bind.WatchOpts, sink chan<- *SMCDeposit) (event.Subscription, error) { +// Solidity: event NotaryDeregistered(notary address, poolIndex uint256, deregisteredPeriod uint256) +func (_SMC *SMCFilterer) WatchNotaryDeregistered(opts *bind.WatchOpts, sink chan<- *SMCNotaryDeregistered) (event.Subscription, error) { - logs, sub, err := _SMC.contract.WatchLogs(opts, "Deposit") + logs, sub, err := _SMC.contract.WatchLogs(opts, "NotaryDeregistered") if err != nil { return nil, err } @@ -808,8 +732,8 @@ func (_SMC *SMCFilterer) WatchDeposit(opts *bind.WatchOpts, sink chan<- *SMCDepo select { case log := <-logs: // New log arrived, parse the event and forward to the user - event := new(SMCDeposit) - if err := _SMC.contract.UnpackLog(event, "Deposit", log); err != nil { + event := new(SMCNotaryDeregistered) + if err := _SMC.contract.UnpackLog(event, "NotaryDeregistered", log); err != nil { return err } event.Raw = log @@ -830,9 +754,9 @@ func (_SMC *SMCFilterer) WatchDeposit(opts *bind.WatchOpts, sink chan<- *SMCDepo }), nil } -// SMCTxToShardIterator is returned from FilterTxToShard and is used to iterate over the raw logs and unpacked data for TxToShard events raised by the SMC contract. -type SMCTxToShardIterator struct { - Event *SMCTxToShard // Event containing the contract specifics and raw log +// SMCNotaryRegisteredIterator is returned from FilterNotaryRegistered and is used to iterate over the raw logs and unpacked data for NotaryRegistered events raised by the SMC contract. +type SMCNotaryRegisteredIterator struct { + Event *SMCNotaryRegistered // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data @@ -846,7 +770,7 @@ type SMCTxToShardIterator struct { // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. -func (it *SMCTxToShardIterator) Next() bool { +func (it *SMCNotaryRegisteredIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false @@ -855,7 +779,7 @@ func (it *SMCTxToShardIterator) Next() bool { if it.done { select { case log := <-it.logs: - it.Event = new(SMCTxToShard) + it.Event = new(SMCNotaryRegistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -870,7 +794,7 @@ func (it *SMCTxToShardIterator) Next() bool { // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: - it.Event = new(SMCTxToShard) + it.Event = new(SMCNotaryRegistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -886,61 +810,42 @@ func (it *SMCTxToShardIterator) Next() bool { } // Error returns any retrieval or parsing error occurred during filtering. -func (it *SMCTxToShardIterator) Error() error { +func (it *SMCNotaryRegisteredIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. -func (it *SMCTxToShardIterator) Close() error { +func (it *SMCNotaryRegisteredIterator) Close() error { it.sub.Unsubscribe() return nil } -// SMCTxToShard represents a TxToShard event raised by the SMC contract. -type SMCTxToShard struct { - To common.Address - ShardId *big.Int - ReceiptId *big.Int +// SMCNotaryRegistered represents a NotaryRegistered event raised by the SMC contract. +type SMCNotaryRegistered struct { + Notary common.Address + PoolIndex *big.Int Raw types.Log // Blockchain specific contextual infos } -// FilterTxToShard is a free log retrieval operation binding the contract event 0xfc322e0c42ee41e0d74b940ceeee9cd5971acdd6ace8ff8010ee7134c31d9ea5. +// FilterNotaryRegistered is a free log retrieval operation binding the contract event 0xa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7. // -// Solidity: event TxToShard(to indexed address, shardId indexed int256, receiptId int256) -func (_SMC *SMCFilterer) FilterTxToShard(opts *bind.FilterOpts, to []common.Address, shardId []*big.Int) (*SMCTxToShardIterator, error) { +// Solidity: event NotaryRegistered(notary address, poolIndex uint256) +func (_SMC *SMCFilterer) FilterNotaryRegistered(opts *bind.FilterOpts) (*SMCNotaryRegisteredIterator, error) { - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var shardIdRule []interface{} - for _, shardIdItem := range shardId { - shardIdRule = append(shardIdRule, shardIdItem) - } - - logs, sub, err := _SMC.contract.FilterLogs(opts, "TxToShard", toRule, shardIdRule) + logs, sub, err := _SMC.contract.FilterLogs(opts, "NotaryRegistered") if err != nil { return nil, err } - return &SMCTxToShardIterator{contract: _SMC.contract, event: "TxToShard", logs: logs, sub: sub}, nil + return &SMCNotaryRegisteredIterator{contract: _SMC.contract, event: "NotaryRegistered", logs: logs, sub: sub}, nil } -// WatchTxToShard is a free log subscription operation binding the contract event 0xfc322e0c42ee41e0d74b940ceeee9cd5971acdd6ace8ff8010ee7134c31d9ea5. +// WatchNotaryRegistered is a free log subscription operation binding the contract event 0xa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7. // -// Solidity: event TxToShard(to indexed address, shardId indexed int256, receiptId int256) -func (_SMC *SMCFilterer) WatchTxToShard(opts *bind.WatchOpts, sink chan<- *SMCTxToShard, to []common.Address, shardId []*big.Int) (event.Subscription, error) { +// Solidity: event NotaryRegistered(notary address, poolIndex uint256) +func (_SMC *SMCFilterer) WatchNotaryRegistered(opts *bind.WatchOpts, sink chan<- *SMCNotaryRegistered) (event.Subscription, error) { - var toRule []interface{} - for _, toItem := range to { - toRule = append(toRule, toItem) - } - var shardIdRule []interface{} - for _, shardIdItem := range shardId { - shardIdRule = append(shardIdRule, shardIdItem) - } - - logs, sub, err := _SMC.contract.WatchLogs(opts, "TxToShard", toRule, shardIdRule) + logs, sub, err := _SMC.contract.WatchLogs(opts, "NotaryRegistered") if err != nil { return nil, err } @@ -950,8 +855,8 @@ func (_SMC *SMCFilterer) WatchTxToShard(opts *bind.WatchOpts, sink chan<- *SMCTx select { case log := <-logs: // New log arrived, parse the event and forward to the user - event := new(SMCTxToShard) - if err := _SMC.contract.UnpackLog(event, "TxToShard", log); err != nil { + event := new(SMCNotaryRegistered) + if err := _SMC.contract.UnpackLog(event, "NotaryRegistered", log); err != nil { return err } event.Raw = log @@ -972,9 +877,9 @@ func (_SMC *SMCFilterer) WatchTxToShard(opts *bind.WatchOpts, sink chan<- *SMCTx }), nil } -// SMCWithdrawIterator is returned from FilterWithdraw and is used to iterate over the raw logs and unpacked data for Withdraw events raised by the SMC contract. -type SMCWithdrawIterator struct { - Event *SMCWithdraw // Event containing the contract specifics and raw log +// SMCNotaryReleasedIterator is returned from FilterNotaryReleased and is used to iterate over the raw logs and unpacked data for NotaryReleased events raised by the SMC contract. +type SMCNotaryReleasedIterator struct { + Event *SMCNotaryReleased // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data @@ -988,7 +893,7 @@ type SMCWithdrawIterator struct { // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. -func (it *SMCWithdrawIterator) Next() bool { +func (it *SMCNotaryReleasedIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false @@ -997,7 +902,7 @@ func (it *SMCWithdrawIterator) Next() bool { if it.done { select { case log := <-it.logs: - it.Event = new(SMCWithdraw) + it.Event = new(SMCNotaryReleased) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -1012,7 +917,7 @@ func (it *SMCWithdrawIterator) Next() bool { // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: - it.Event = new(SMCWithdraw) + it.Event = new(SMCNotaryReleased) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -1028,41 +933,42 @@ func (it *SMCWithdrawIterator) Next() bool { } // Error returns any retrieval or parsing error occurred during filtering. -func (it *SMCWithdrawIterator) Error() error { +func (it *SMCNotaryReleasedIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. -func (it *SMCWithdrawIterator) Close() error { +func (it *SMCNotaryReleasedIterator) Close() error { it.sub.Unsubscribe() return nil } -// SMCWithdraw represents a Withdraw event raised by the SMC contract. -type SMCWithdraw struct { - Index *big.Int - Raw types.Log // Blockchain specific contextual infos +// SMCNotaryReleased represents a NotaryReleased event raised by the SMC contract. +type SMCNotaryReleased struct { + Notary common.Address + PoolIndex *big.Int + Raw types.Log // Blockchain specific contextual infos } -// FilterWithdraw is a free log retrieval operation binding the contract event 0xe13f360aa18d414ccdb598da6c447faa89d0477ffc7549dab5678fca76910b8c. +// FilterNotaryReleased is a free log retrieval operation binding the contract event 0xaee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680. // -// Solidity: event Withdraw(index int256) -func (_SMC *SMCFilterer) FilterWithdraw(opts *bind.FilterOpts) (*SMCWithdrawIterator, error) { +// Solidity: event NotaryReleased(notary address, poolIndex uint256) +func (_SMC *SMCFilterer) FilterNotaryReleased(opts *bind.FilterOpts) (*SMCNotaryReleasedIterator, error) { - logs, sub, err := _SMC.contract.FilterLogs(opts, "Withdraw") + logs, sub, err := _SMC.contract.FilterLogs(opts, "NotaryReleased") if err != nil { return nil, err } - return &SMCWithdrawIterator{contract: _SMC.contract, event: "Withdraw", logs: logs, sub: sub}, nil + return &SMCNotaryReleasedIterator{contract: _SMC.contract, event: "NotaryReleased", logs: logs, sub: sub}, nil } -// WatchWithdraw is a free log subscription operation binding the contract event 0xe13f360aa18d414ccdb598da6c447faa89d0477ffc7549dab5678fca76910b8c. +// WatchNotaryReleased is a free log subscription operation binding the contract event 0xaee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680. // -// Solidity: event Withdraw(index int256) -func (_SMC *SMCFilterer) WatchWithdraw(opts *bind.WatchOpts, sink chan<- *SMCWithdraw) (event.Subscription, error) { +// Solidity: event NotaryReleased(notary address, poolIndex uint256) +func (_SMC *SMCFilterer) WatchNotaryReleased(opts *bind.WatchOpts, sink chan<- *SMCNotaryReleased) (event.Subscription, error) { - logs, sub, err := _SMC.contract.WatchLogs(opts, "Withdraw") + logs, sub, err := _SMC.contract.WatchLogs(opts, "NotaryReleased") if err != nil { return nil, err } @@ -1072,8 +978,8 @@ func (_SMC *SMCFilterer) WatchWithdraw(opts *bind.WatchOpts, sink chan<- *SMCWit select { case log := <-logs: // New log arrived, parse the event and forward to the user - event := new(SMCWithdraw) - if err := _SMC.contract.UnpackLog(event, "Withdraw", log); err != nil { + event := new(SMCNotaryReleased) + if err := _SMC.contract.UnpackLog(event, "NotaryReleased", log); err != nil { return err } event.Raw = log diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index c39037064..0524877ef 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -87,7 +87,8 @@ contract SMC { // Get the most recent block number before the period started uint latestBlock = period * PERIOD_LENGTH - 1; - uint index = uint(keccak256(block.blockhash(latestBlock), _index, shardId)) % sampleSize; + uint latestBlockHash = uint(block.blockhash(latestBlock)); + uint index = uint(keccak256(latestBlockHash, _index, shardId)) % sampleSize; return notaryPool[index]; } diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 9dd735474..9c204f6f6 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -56,6 +56,7 @@ func TestNotaryRegister(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) + // initializes back end with 3 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -420,6 +421,7 @@ func TestCommitteeListsAreDifferent(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) + // initializes back end with 1000 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -469,6 +471,7 @@ func TestGetCommitteeWithNonMember(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) + // initializes back end with 11 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -511,6 +514,7 @@ func TestGetCommitteeAfterDeregisters(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) + // initializes back end with 10 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key From 08325ed7d4ac6bad8823da7d7ce133ddc1eb9def Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Tue, 24 Apr 2018 09:01:16 -0700 Subject: [PATCH 20/30] sharding: abi name changes fixed other packages Former-commit-id: eeb039b0e54b958cd64174495c8632ca66e240d1 [formerly dc0fb2653ee915b4033d3ed8cca10a4204ae7de8] Former-commit-id: b138547efd51ac985ff7c759eea5d288149b460a --- sharding/collator/collator.go | 31 +++++++++++++++--------------- sharding/collator/collator_test.go | 6 +++--- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/sharding/collator/collator.go b/sharding/collator/collator.go index 9f5e00da4..8361ddd87 100644 --- a/sharding/collator/collator.go +++ b/sharding/collator/collator.go @@ -56,21 +56,22 @@ func subscribeBlockHeaders(c client.Client) error { // conditions are met func checkSMCForCollator(c client.Client, head *types.Header) error { log.Info("Checking if we are an eligible collation collator for a shard...") - period := big.NewInt(0).Div(head.Number, big.NewInt(sharding.PeriodLength)) for s := int64(0); s < sharding.ShardCount; s++ { // Checks if we are an eligible collator according to the SMC - addr, err := c.SMCCaller().GetEligibleCollator(&bind.CallOpts{}, big.NewInt(s), period) + for i := int64(0); i < sharding.NotaryCommitSize; s++ { + addr, err := c.SMCCaller().GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(s), i) - if err != nil { - return err - } - - // If output is non-empty and the addr == coinbase - if addr == c.Account().Address { - log.Info(fmt.Sprintf("Selected as collator on shard: %d", s)) - err := submitCollation(s) if err != nil { - return fmt.Errorf("could not add collation. %v", err) + return err + } + + // If output is non-empty and the addr == coinbase + if addr == c.Account().Address { + log.Info(fmt.Sprintf("Selected as collator on shard: %d", s)) + err := submitCollation(s) + if err != nil { + return fmt.Errorf("could not add collation. %v", err) + } } } } @@ -85,11 +86,11 @@ func checkSMCForCollator(c client.Client, head *types.Header) error { func isAccountInCollatorPool(c client.Client) (bool, error) { account := c.Account() // Checks if our deposit has gone through according to the SMC - b, err := c.SMCCaller().IsCollatorDeposited(&bind.CallOpts{}, account.Address) - if !b && err != nil { + b, err := c.SMCCaller().NotaryRegistry(&bind.CallOpts{}, account.Address) + if !b.Deposited && err != nil { log.Warn(fmt.Sprintf("Account %s not in collator pool.", account.Address.String())) } - return b, err + return b.Deposited, err } // submitCollation interacts with the SMC directly to add a collation header @@ -132,7 +133,7 @@ func joinCollatorPool(c client.Client) error { return fmt.Errorf("unable to intiate the deposit transaction: %v", err) } - tx, err := c.SMCTransactor().Deposit(txOps) + tx, err := c.SMCTransactor().RegisterNotary(txOps) if err != nil { return fmt.Errorf("unable to deposit eth and become a collator: %v", err) } diff --git a/sharding/collator/collator_test.go b/sharding/collator/collator_test.go index 2843607f2..d0a82cefd 100644 --- a/sharding/collator/collator_test.go +++ b/sharding/collator/collator_test.go @@ -87,7 +87,7 @@ func TestIsAccountInCollatorPool(t *testing.T) { txOpts := transactOpts() // deposit in collator pool, then it should return true txOpts.Value = sharding.NotaryDeposit - if _, err := smc.Deposit(txOpts); err != nil { + if _, err := smc.RegisterNotary(txOpts); err != nil { t.Fatalf("Failed to deposit: %v", err) } backend.Commit() @@ -105,7 +105,7 @@ func TestJoinCollatorPool(t *testing.T) { client := &mockClient{smc, t} // There should be no collators initially - numCollators, err := smc.NumCollators(&bind.CallOpts{}) + numCollators, err := smc.NotaryPoolLength(&bind.CallOpts{}) if err != nil { t.Fatal(err) } @@ -120,7 +120,7 @@ func TestJoinCollatorPool(t *testing.T) { backend.Commit() // Now there should be one collator - numCollators, err = smc.NumCollators(&bind.CallOpts{}) + numCollators, err = smc.NotaryPoolLength(&bind.CallOpts{}) if err != nil { t.Fatal(err) } From 0b7df21505d5b001b83210b1b4aa686c75cfd940 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Tue, 24 Apr 2018 10:18:45 -0700 Subject: [PATCH 21/30] sharding: fixed lint Former-commit-id: a333578841a9058f1e7f298970fb1460ac5eefe1 [formerly 4dcb80be36a3d4d59e0c950e318ae277c792a725] Former-commit-id: 576570909a92d0858cae2fa2fd8f6bf7088f06f8 --- sharding/collator/collator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding/collator/collator.go b/sharding/collator/collator.go index 8361ddd87..a706bf266 100644 --- a/sharding/collator/collator.go +++ b/sharding/collator/collator.go @@ -59,7 +59,7 @@ func checkSMCForCollator(c client.Client, head *types.Header) error { for s := int64(0); s < sharding.ShardCount; s++ { // Checks if we are an eligible collator according to the SMC for i := int64(0); i < sharding.NotaryCommitSize; s++ { - addr, err := c.SMCCaller().GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(s), i) + addr, err := c.SMCCaller().GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(s), big.NewInt(i)) if err != nil { return err From 4e45d1882c25507516ebbc8c7ee6f6544c6db777 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Tue, 24 Apr 2018 11:22:55 -0700 Subject: [PATCH 22/30] sharding: fixed lint Former-commit-id: cecf8e888992de3583c222e98f1e3e4c26c48924 [formerly 67381715d66b4a512d9e884a257ab0609fd81d33] Former-commit-id: 66fa59bb52e8343843f10247d668e2b3fe8c892f --- sharding/contracts/sharding_manager.go | 2 +- sharding/contracts/sharding_manager_test.go | 24 ++++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/sharding/contracts/sharding_manager.go b/sharding/contracts/sharding_manager.go index 016dab114..b2ea30b58 100644 --- a/sharding/contracts/sharding_manager.go +++ b/sharding/contracts/sharding_manager.go @@ -19,7 +19,7 @@ import ( const SMCABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationTrees\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deregisterNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"periodHead\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"registerNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"notaryRegistry\",\"outputs\":[{\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"},{\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"name\":\"deposited\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"releaseNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"notaryPool\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"getNotaryInCommittee\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"uint256\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"addHeader\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"computeHeaderHash\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationHeaders\",\"outputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"notaryPoolLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"shardId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"period\",\"type\":\"int128\"},{\"indexed\":false,\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"HeaderAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryRegistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"}],\"name\":\"NotaryDeregistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryReleased\",\"type\":\"event\"}]" // SMCBin is the compiled bytecode used for deploying new contracts. -const SMCBin = `0x608060405234801561001057600080fd5b50610921806100206000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166303dde97781146100be57806358377bd1146100eb578063584475db1461011457806368e9513e1461012c5780636bdd3271146101345780639910851d14610175578063a81f45101461018a578063b09f427e146101be578063b8bc055f146101d9578063b9505ea414610203578063b9d8ef9614610230578063f6f67d361461027a575b600080fd5b3480156100ca57600080fd5b506100d960043560243561028f565b60408051918252519081900360200190f35b3480156100f757600080fd5b506101006102ac565b604080519115158252519081900360200190f35b34801561012057600080fd5b506100d96004356103df565b6101006103f1565b34801561014057600080fd5b50610155600160a060020a03600435166105af565b604080519384526020840192909252151582820152519081900360600190f35b34801561018157600080fd5b506101006105d2565b34801561019657600080fd5b506101a2600435610705565b60408051600160a060020a039092168252519081900360200190f35b3480156101ca57600080fd5b506101a260043560243561072d565b3480156101e557600080fd5b50610100600435602435604435600160a060020a03606435166107bb565b34801561020f57600080fd5b506100d9600435602435604435606435600160a060020a03608435166107c5565b34801561023c57600080fd5b5061024b6004356024356107d0565b60408051948552602085019390935283830191909152600160a060020a03166060830152519081900360800190f35b34801561028657600080fd5b506100d961080a565b600260209081526000928352604080842090915290825290205481565b33600160a060020a0381166000908152600160208190526040822090810154600290910154919291839060ff1615156102e457600080fd5b82600160a060020a03166000838154811015156102fd57fe5b600091825260209091200154600160a060020a03161461031c57600080fd5b610324610810565b5050600160a060020a0382166000908152600160205260409020600543049081905561034f8261083f565b600080548390811061035d57fe5b600091825260209182902001805473ffffffffffffffffffffffffffffffffffffffff191690556005805460001901905560408051600160a060020a0386168152918201849052818101839052517f90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a759181900360600190a16001935050505090565b600b6020526000908152604090205481565b33600160a060020a038116600090815260016020526040812060020154909190829060ff161561042057600080fd5b34683635c9adc5dea000001461043557600080fd5b61043d610810565b506104466108b0565b156104a95750600554600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0384161790556104f2565b6104b16108b7565b9050816000828154811015156104c357fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a031602179055505b6005805460019081019091556040805160608101825260008082526020808301868152838501868152600160a060020a0389168452918690529390912091518255915192810192909255516002909101805460ff1916911515919091179055600954811061056257600181016009555b60408051600160a060020a03841681526020810183905281517fa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7929181900390910190a160019250505090565b600160208190526000918252604090912080549181015460029091015460ff1683565b33600160a060020a0381166000908152600160208190526040822080820154600290910154929392909160ff90911615151461060d57600080fd5b600160a060020a038216600090815260016020526040902054151561063157600080fd5b600160a060020a038216600090815260016020526040902054613f0001600543041161065c57600080fd5b600160a060020a03821660008181526001602081905260408083208381559182018390556002909101805460ff1916905551683635c9adc5dea000009082818181858883f193505050501580156106b7573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517faee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680929181900390910190a160019250505090565b600080548290811061071357fe5b600091825260209091200154600160a060020a0316905081565b600080808080600543049350600a5484111561074d576009549250610753565b60085492505b60408051600019600587020180408252602082018990528183018a90529151908190036060019020909250839081151561078957fe5b06905060008181548110151561079b57fe5b600091825260209091200154600160a060020a0316979650505050505050565b6000949350505050565b600095945050505050565b60036020818152600093845260408085209091529183529120805460018201546002830154929093015490929190600160a060020a031684565b60055481565b600a54600090600543049081101561082b576000915061083b565b600954600855600a819055600191505b5090565b600754600654141561088557600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f018190556108a4565b80600660075481548110151561089757fe5b6000918252602090912001555b50600780546001019055565b6007541590565b600060016007541115156108ca57600080fd5b6007805460001901908190556006805490919081106108e557fe5b90600052602060002001549050905600a165627a7a72305820f09036677376fe46add7ec634264b1b42a1568f2d25123be3958f3625d5500da0029` +const SMCBin = `0x608060405234801561001057600080fd5b50610928806100206000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166303dde97781146100be57806358377bd1146100eb578063584475db1461011457806368e9513e1461012c5780636bdd3271146101345780639910851d14610175578063a81f45101461018a578063b09f427e146101be578063b8bc055f146101d9578063b9505ea414610203578063b9d8ef9614610230578063f6f67d361461027a575b600080fd5b3480156100ca57600080fd5b506100d960043560243561028f565b60408051918252519081900360200190f35b3480156100f757600080fd5b506101006102ac565b604080519115158252519081900360200190f35b34801561012057600080fd5b506100d96004356103df565b6101006103f1565b34801561014057600080fd5b50610155600160a060020a03600435166105af565b604080519384526020840192909252151582820152519081900360600190f35b34801561018157600080fd5b506101006105d2565b34801561019657600080fd5b506101a2600435610705565b60408051600160a060020a039092168252519081900360200190f35b3480156101ca57600080fd5b506101a260043560243561072d565b3480156101e557600080fd5b50610100600435602435604435600160a060020a03606435166107c2565b34801561020f57600080fd5b506100d9600435602435604435606435600160a060020a03608435166107cc565b34801561023c57600080fd5b5061024b6004356024356107d7565b60408051948552602085019390935283830191909152600160a060020a03166060830152519081900360800190f35b34801561028657600080fd5b506100d9610811565b600260209081526000928352604080842090915290825290205481565b33600160a060020a0381166000908152600160208190526040822090810154600290910154919291839060ff1615156102e457600080fd5b82600160a060020a03166000838154811015156102fd57fe5b600091825260209091200154600160a060020a03161461031c57600080fd5b610324610817565b5050600160a060020a0382166000908152600160205260409020600543049081905561034f82610846565b600080548390811061035d57fe5b600091825260209182902001805473ffffffffffffffffffffffffffffffffffffffff191690556005805460001901905560408051600160a060020a0386168152918201849052818101839052517f90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a759181900360600190a16001935050505090565b600b6020526000908152604090205481565b33600160a060020a038116600090815260016020526040812060020154909190829060ff161561042057600080fd5b34683635c9adc5dea000001461043557600080fd5b61043d610817565b506104466108b7565b156104a95750600554600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0384161790556104f2565b6104b16108be565b9050816000828154811015156104c357fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a031602179055505b6005805460019081019091556040805160608101825260008082526020808301868152838501868152600160a060020a0389168452918690529390912091518255915192810192909255516002909101805460ff1916911515919091179055600954811061056257600181016009555b60408051600160a060020a03841681526020810183905281517fa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7929181900390910190a160019250505090565b600160208190526000918252604090912080549181015460029091015460ff1683565b33600160a060020a0381166000908152600160208190526040822080820154600290910154929392909160ff90911615151461060d57600080fd5b600160a060020a038216600090815260016020526040902054151561063157600080fd5b600160a060020a038216600090815260016020526040902054613f0001600543041161065c57600080fd5b600160a060020a03821660008181526001602081905260408083208381559182018390556002909101805460ff1916905551683635c9adc5dea000009082818181858883f193505050501580156106b7573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517faee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680929181900390910190a160019250505090565b600080548290811061071357fe5b600091825260209091200154600160a060020a0316905081565b60008080808080600543049450600a5485111561074e576009549350610754565b60085493505b6040805160001960058802018040808352602083018b90528284018c9052925191829003606001909120909450909250849081151561078f57fe5b0690506000818154811015156107a157fe5b600091825260209091200154600160a060020a031698975050505050505050565b6000949350505050565b600095945050505050565b60036020818152600093845260408085209091529183529120805460018201546002830154929093015490929190600160a060020a031684565b60055481565b600a5460009060054304908110156108325760009150610842565b600954600855600a819055600191505b5090565b600754600654141561088c57600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f018190556108ab565b80600660075481548110151561089e57fe5b6000918252602090912001555b50600780546001019055565b6007541590565b600060016007541115156108d157600080fd5b6007805460001901908190556006805490919081106108ec57fe5b90600052602060002001549050905600a165627a7a72305820d453a229f7690048c16d8e76567fa0295b766cfeb78ef0750763de17190630300029` // DeploySMC deploys a new Ethereum contract, binding an instance of SMC to it. func DeploySMC(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *SMC, error) { diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 9c204f6f6..9a691c79e 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -77,7 +77,7 @@ func TestNotaryRegister(t *testing.T) { t.Fatalf("Can't get notary registry info: %v", err) } - if notary.Deposited != false { + if notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -89,7 +89,7 @@ func TestNotaryRegister(t *testing.T) { notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[0]) - if notary.Deposited != true && + if !notary.Deposited && notary.PoolIndex.Cmp(big.NewInt(0)) != 0 && notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { t.Fatalf("Incorrect notary registry. Want - deposited:true, index:0, period:0"+ @@ -109,7 +109,7 @@ func TestNotaryRegister(t *testing.T) { notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[1]) - if notary.Deposited != true && + if !notary.Deposited && notary.PoolIndex.Cmp(big.NewInt(1)) != 0 && notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { t.Fatalf("Incorrect notary registry. Want - deposited:true, index:1, period:0"+ @@ -118,7 +118,7 @@ func TestNotaryRegister(t *testing.T) { notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[2]) - if notary.Deposited != true && + if !notary.Deposited && notary.PoolIndex.Cmp(big.NewInt(2)) != 0 && notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { t.Fatalf("Incorrect notary registry. Want - deposited:true, index:2, period:0"+ @@ -148,7 +148,7 @@ func TestNotaryRegisterInsufficientEther(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != false { + if notary.Deposited { t.Fatalf("Notary deposited with insufficient fund") } @@ -171,7 +171,7 @@ func TestNotaryDoubleRegisters(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -207,7 +207,7 @@ func TestNotaryDeregister(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -255,7 +255,7 @@ func TestNotaryDeregisterThenRegister(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -300,7 +300,7 @@ func TestNotaryRelease(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -343,7 +343,7 @@ func TestNotaryRelease(t *testing.T) { t.Fatalf("Can't get notary registry info: %v", err) } - if notary.Deposited != false { + if notary.Deposited { t.Fatalf("Notary deposit flag should be false after released") } @@ -368,7 +368,7 @@ func TestNotaryInstantRelease(t *testing.T) { notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } @@ -403,7 +403,7 @@ func TestNotaryInstantRelease(t *testing.T) { t.Fatalf("Can't get notary registry info: %v", err) } - if notary.Deposited != true { + if !notary.Deposited { t.Fatalf("Notary deposit flag should be true before released") } From 150f0ae58dc4f094fcd0fc148a29baa81c5a1740 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Tue, 24 Apr 2018 21:55:32 -0700 Subject: [PATCH 23/30] sharding: latest round of feedback Former-commit-id: e37429c965bb98a0155f85351f76e0db2d0e2a07 [formerly 1d3ad1e172e1d0a80c66a2bd44a8fac7414d439a] Former-commit-id: addf37b75b2c9952da0274bbb57df27b096455fb --- sharding/collator/collator.go | 2 +- sharding/contracts/sharding_manager_test.go | 137 ++++++++++---------- 2 files changed, 71 insertions(+), 68 deletions(-) diff --git a/sharding/collator/collator.go b/sharding/collator/collator.go index a706bf266..9b566ab1a 100644 --- a/sharding/collator/collator.go +++ b/sharding/collator/collator.go @@ -65,7 +65,7 @@ func checkSMCForCollator(c client.Client, head *types.Header) error { return err } - // If output is non-empty and the addr == coinbase + // If the account is selected as collator, submit collation if addr == c.Account().Address { log.Info(fmt.Sprintf("Selected as collator on shard: %d", s)) err := submitCollation(s) diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 9a691c79e..8dfa8b7ab 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -25,6 +25,7 @@ var ( accountBalance2000Eth, _ = new(big.Int).SetString("2000000000000000000000", 10) notaryDepositInsufficient, _ = new(big.Int).SetString("999000000000000000000", 10) notaryDeposit, _ = new(big.Int).SetString("1000000000000000000000", 10) + FastForward100Blocks = 100 smcConfig = SMCConfig{ notaryLockupLenght: new(big.Int).SetInt64(1), proposerLockupLength: new(big.Int).SetInt64(1), @@ -78,7 +79,7 @@ func TestNotaryRegister(t *testing.T) { } if notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } // Test notary 0 has registered @@ -89,10 +90,10 @@ func TestNotaryRegister(t *testing.T) { notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[0]) - if !notary.Deposited && - notary.PoolIndex.Cmp(big.NewInt(0)) != 0 && + if !notary.Deposited || + notary.PoolIndex.Cmp(big.NewInt(0)) != 0 || notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect notary registry. Want - deposited:true, index:0, period:0"+ + t.Errorf("Incorrect notary registry. Want - deposited:true, index:0, period:0"+ "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) } @@ -109,19 +110,19 @@ func TestNotaryRegister(t *testing.T) { notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[1]) - if !notary.Deposited && - notary.PoolIndex.Cmp(big.NewInt(1)) != 0 && + if !notary.Deposited || + notary.PoolIndex.Cmp(big.NewInt(1)) != 0 || notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect notary registry. Want - deposited:true, index:1, period:0"+ + t.Errorf("Incorrect notary registry. Want - deposited:true, index:1, period:0"+ "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) } notary, err = smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[2]) - if !notary.Deposited && - notary.PoolIndex.Cmp(big.NewInt(2)) != 0 && + if !notary.Deposited || + notary.PoolIndex.Cmp(big.NewInt(2)) != 0 || notary.DeregisteredPeriod.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect notary registry. Want - deposited:true, index:2, period:0"+ + t.Errorf("Incorrect notary registry. Want - deposited:true, index:2, period:0"+ "Got - deposited:%v, index:%v, period:%v ", notary.Deposited, notary.PoolIndex, notary.DeregisteredPeriod) } @@ -131,7 +132,7 @@ func TestNotaryRegister(t *testing.T) { t.Fatalf("Failed to get notary pool length: %v", err) } if numNotaries.Cmp(big.NewInt(3)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 3, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 3, Got: %v", numNotaries) } } @@ -142,19 +143,22 @@ func TestNotaryRegisterInsufficientEther(t *testing.T) { txOpts.Value = notaryDepositInsufficient _, _, smc, _ := deploySMCContract(backend, mainKey) - smc.RegisterNotary(txOpts) - backend.Commit() + _, err := smc.RegisterNotary(txOpts) + if err == nil { + t.Errorf("Notary register should have failed with insufficient deposit") + } notary, _ := smc.NotaryRegistry(&bind.CallOpts{}, addr) numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if notary.Deposited { - t.Fatalf("Notary deposited with insufficient fund") + t.Errorf("Notary deposited with insufficient fund") } if numNotaries.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } + } func TestNotaryDoubleRegisters(t *testing.T) { @@ -172,24 +176,21 @@ func TestNotaryDoubleRegisters(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if !notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } // Notary 0 registers again - _, _ = smc.RegisterNotary(txOpts) - backend.Commit() - - if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + _, err := smc.RegisterNotary(txOpts) + if err == nil { + t.Errorf("Notary register should have failed with double registers") + } + if numNotaries.Cmp(big.NewInt(1)) != 0 { + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } - - //ctx := context.Background() - //_, _ = backend.TransactionReceipt(ctx, tx.Hash()) - ////t.Log(r.CumulativeGasUsed) } @@ -208,15 +209,15 @@ func TestNotaryDeregister(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if !notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } - // Fast forward 100 blocks - for i := 0; i < 100; i++ { + // Fast forward 100 blocks to check notary's deregistered period field is set correctly + for i := 0; i < FastForward100Blocks; i++ { backend.Commit() } @@ -230,14 +231,14 @@ func TestNotaryDeregister(t *testing.T) { // Verify notary has saved the deregistered period as: current block number / period length notary, _ = smc.NotaryRegistry(&bind.CallOpts{}, addr) - currentPeriod := big.NewInt(int64(100 / sharding.PeriodLength)) + currentPeriod := big.NewInt(int64(FastForward100Blocks) / sharding.PeriodLength) if currentPeriod.Cmp(notary.DeregisteredPeriod) != 0 { - t.Fatalf("Incorrect notary degister period. Want: %v, Got: %v ", currentPeriod, notary.DeregisteredPeriod) + t.Errorf("Incorrect notary degister period. Want: %v, Got: %v ", currentPeriod, notary.DeregisteredPeriod) } numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } } @@ -256,11 +257,11 @@ func TestNotaryDeregisterThenRegister(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if !notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } // Notary 0 deregisters @@ -273,7 +274,7 @@ func TestNotaryDeregisterThenRegister(t *testing.T) { numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } // Notary 0 re-registers again @@ -282,7 +283,7 @@ func TestNotaryDeregisterThenRegister(t *testing.T) { numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } } @@ -301,15 +302,15 @@ func TestNotaryRelease(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if !notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } - // Fast forward 10 blocks - for i := 0; i < 10; i++ { + // Fast forward to the next period to deregister + for i := 0; i < int(sharding.PeriodLength); i++ { backend.Commit() } @@ -323,7 +324,7 @@ func TestNotaryRelease(t *testing.T) { numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } // Fast forward until lockup ends @@ -344,13 +345,16 @@ func TestNotaryRelease(t *testing.T) { } if notary.Deposited { - t.Fatalf("Notary deposit flag should be false after released") + t.Errorf("Notary deposit flag should be false after released") } balance, err := backend.BalanceAt(ctx, addr, nil) + if err != nil { + t.Errorf("Can't get account balance, err: %s", err) + } if balance.Cmp(notaryDeposit) < 0 { - t.Fatalf("Notary did not receive deposit after lock up ends") + t.Errorf("Notary did not receive deposit after lock up ends") } } @@ -369,15 +373,15 @@ func TestNotaryInstantRelease(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if !notary.Deposited { - t.Fatalf("Notary has not registered. Got deposited flag: %v", notary.Deposited) + t.Errorf("Notary has not registered. Got deposited flag: %v", notary.Deposited) } if numNotaries.Cmp(big.NewInt(1)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 1, Got: %v", numNotaries) } - // Fast forward 10 blocks - for i := 0; i < 10; i++ { + // Fast forward to the next period to deregister + for i := 0; i < int(sharding.PeriodLength); i++ { backend.Commit() } @@ -394,7 +398,7 @@ func TestNotaryInstantRelease(t *testing.T) { t.Fatalf("Incorrect count from notary pool. Want: 0, Got: %v", numNotaries) } - // Notary 0 releases before lockup ends + // Notary 0 tries to release before lockup ends _, err = smc.ReleaseNotary(txOpts) backend.Commit() @@ -404,24 +408,24 @@ func TestNotaryInstantRelease(t *testing.T) { } if !notary.Deposited { - t.Fatalf("Notary deposit flag should be true before released") + t.Errorf("Notary deposit flag should be true before released") } balance, err := backend.BalanceAt(ctx, addr, nil) if balance.Cmp(notaryDeposit) > 0 { - t.Fatalf("Notary received deposit before lockup ends") + t.Errorf("Notary received deposit before lockup ends") } } func TestCommitteeListsAreDifferent(t *testing.T) { - const notaryCount = 1000 + const notaryCount = 10000 var notaryPoolAddr [notaryCount]common.Address var notaryPoolPrivKeys [notaryCount]*ecdsa.PrivateKey var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) - // initializes back end with 1000 accounts and each with 2000 eth balances + // initializes back end with 10000 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -436,15 +440,15 @@ func TestCommitteeListsAreDifferent(t *testing.T) { backend := backends.NewSimulatedBackend(genesis) _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) - // register 1000 notaries to SMC + // register 10000 notaries to SMC for i := 0; i < notaryCount; i++ { smc.RegisterNotary(txOpts[i]) backend.Commit() } numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) - if numNotaries.Cmp(big.NewInt(1000)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 1000, Got: %v", numNotaries) + if numNotaries.Cmp(big.NewInt(10000)) != 0 { + t.Errorf("Incorrect count from notary pool. Want: 1000, Got: %v", numNotaries) } // get a list of sampled notaries from shard 0 @@ -458,8 +462,7 @@ func TestCommitteeListsAreDifferent(t *testing.T) { for i := 0; i < int(sharding.NotaryCommitSize); i++ { addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(1), big.NewInt(int64(i))) if shard0CommitteeList[i] == addr.String() { - t.Log(i) - t.Fatalf("Shard 0 committee list is identical to shard 1's committee list") + t.Errorf("Shard 0 committee list is identical to shard 1's committee list") } } } @@ -471,7 +474,7 @@ func TestGetCommitteeWithNonMember(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) - // initializes back end with 11 accounts and each with 2000 eth balances + // initialize back end with 11 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -486,7 +489,7 @@ func TestGetCommitteeWithNonMember(t *testing.T) { backend := backends.NewSimulatedBackend(genesis) _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) - // registers 10 notaries to SMC, leave 1 address free + // register 10 notaries to SMC, leave 1 address free for i := 0; i < 10; i++ { smc.RegisterNotary(txOpts[i]) backend.Commit() @@ -497,11 +500,11 @@ func TestGetCommitteeWithNonMember(t *testing.T) { t.Fatalf("Incorrect count from notary pool. Want: 135, Got: %v", numNotaries) } - // verify the free address can't be sampled from the committee list + // verify the unregistered account is not in the notary pool list for i := 0; i < 10; i++ { addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(int64(i))) if notaryPoolAddr[10].String() == addr.String() { - t.Fatalf("Account %s is not a notary", notaryPoolAddr[10].String()) + t.Errorf("Account %s is not a notary", notaryPoolAddr[10].String()) } } @@ -514,7 +517,7 @@ func TestGetCommitteeAfterDeregisters(t *testing.T) { var txOpts [notaryCount]*bind.TransactOpts genesis := make(core.GenesisAlloc) - // initializes back end with 10 accounts and each with 2000 eth balances + // initialize back end with 10 accounts and each with 2000 eth balances for i := 0; i < notaryCount; i++ { key, _ := crypto.GenerateKey() notaryPoolPrivKeys[i] = key @@ -537,7 +540,7 @@ func TestGetCommitteeAfterDeregisters(t *testing.T) { numNotaries, _ := smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(10)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 10, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 10, Got: %v", numNotaries) } // deregister notary 0 from SMC @@ -547,14 +550,14 @@ func TestGetCommitteeAfterDeregisters(t *testing.T) { numNotaries, _ = smc.NotaryPoolLength(&bind.CallOpts{}) if numNotaries.Cmp(big.NewInt(9)) != 0 { - t.Fatalf("Incorrect count from notary pool. Want: 9, Got: %v", numNotaries) + t.Errorf("Incorrect count from notary pool. Want: 9, Got: %v", numNotaries) } - // verify degistered notary 0 can't be sampled + // verify degistered notary 0 is not in the notary pool list for i := 0; i < 10; i++ { addr, _ := smc.GetNotaryInCommittee(&bind.CallOpts{}, big.NewInt(0), big.NewInt(int64(i))) if notaryPoolAddr[0].String() == addr.String() { - t.Fatalf("Account %s is not a notary", notaryPoolAddr[0].String()) + t.Errorf("Account %s is not a notary", notaryPoolAddr[0].String()) } } } From 791576b204da61a42314e017fed087de48bdb59d Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 26 Apr 2018 11:10:31 -0700 Subject: [PATCH 24/30] sharding: \collator\notary\ on all files Former-commit-id: 859723690bc327d7df9ffdd8f7ae247c05e1e1bf [formerly e2603e530217645b3f1fa180613ba27dca74e2f3] Former-commit-id: c812bd611996a0a8a344064199163aa709ee3f24 --- cmd/geth/main.go | 2 +- cmd/geth/shardingcmd.go | 20 ++++++------ cmd/utils/flags.go | 2 +- sharding/client/client.go | 4 +-- sharding/collator/collator.go | 48 ++++++++++++++-------------- sharding/collator/collator_client.go | 26 +++++++-------- sharding/collator/collator_test.go | 38 +++++++++++----------- 7 files changed, 70 insertions(+), 70 deletions(-) diff --git a/cmd/geth/main.go b/cmd/geth/main.go index 99cdcb9f3..89e676781 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -168,7 +168,7 @@ func init() { attachCommand, javascriptCommand, // See shardingcmd.go: - collatorClientCommand, + notaryClientCommand, proposerClientCommand, // See misccmd.go: makecacheCommand, diff --git a/cmd/geth/shardingcmd.go b/cmd/geth/shardingcmd.go index fff929731..ca03c7bea 100644 --- a/cmd/geth/shardingcmd.go +++ b/cmd/geth/shardingcmd.go @@ -1,7 +1,7 @@ package main import ( - "github.com/ethereum/go-ethereum/sharding/collator" + "github.com/ethereum/go-ethereum/sharding/notary" "github.com/ethereum/go-ethereum/sharding/proposer" "github.com/ethereum/go-ethereum/cmd/utils" @@ -9,16 +9,16 @@ import ( ) var ( - collatorClientCommand = cli.Command{ - Action: utils.MigrateFlags(collatorClient), - Name: "sharding-collator", - Aliases: []string{"shard-collator"}, - Usage: "Start a sharding collator client", + notaryClientCommand = cli.Command{ + Action: utils.MigrateFlags(notaryClient), + Name: "sharding-notary", + Aliases: []string{"shard-notary"}, + Usage: "Start a sharding notary client", ArgsUsage: "[endpoint]", Flags: []cli.Flag{utils.DataDirFlag, utils.PasswordFileFlag, utils.NetworkIdFlag, utils.IPCPathFlag, utils.DepositFlag}, Category: "SHARDING COMMANDS", Description: ` -Launches a sharding collator client that connects to a running geth node and submit collations to a Sharding Manager Contract. This feature is a work in progress. +Launches a sharding notary client that connects to a running geth node and submit collations to a Sharding Manager Contract. This feature is a work in progress. `, } proposerClientCommand = cli.Command{ @@ -30,13 +30,13 @@ Launches a sharding collator client that connects to a running geth node and sub Flags: []cli.Flag{utils.DataDirFlag, utils.PasswordFileFlag, utils.NetworkIdFlag, utils.IPCPathFlag}, Category: "SHARDING COMMANDS", Description: ` -Launches a sharding proposer client that connects to a running geth node and proposes collations to collator node. This feature is a work in progress. +Launches a sharding proposer client that connects to a running geth node and proposes collations to notary node. This feature is a work in progress. `, } ) -func collatorClient(ctx *cli.Context) error { - c := collator.NewCollator(ctx) +func notaryClient(ctx *cli.Context) error { + c := notary.NewCollator(ctx) return c.Start() } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 132d51d61..968a92aca 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -536,7 +536,7 @@ var ( //Sharding Settings DepositFlag = cli.BoolFlag{ Name: "deposit", - Usage: "To become a collator with your sharding client, 100 ETH will be deposited from user's account into SMC ", + Usage: "To become a notary with your sharding client, 100 ETH will be deposited from user's account into SMC ", } ) diff --git a/sharding/client/client.go b/sharding/client/client.go index 0ff634c38..8a54f15e0 100644 --- a/sharding/client/client.go +++ b/sharding/client/client.go @@ -33,7 +33,7 @@ const ( clientIdentifier = "geth" // Used to determine the ipc name. ) -// General client for Collator/Proposer. Communicates to Geth node via JSON RPC. +// General client for Notary/Proposer. Communicates to Geth node via JSON RPC. type shardingClient struct { endpoint string // Endpoint to JSON RPC @@ -96,7 +96,7 @@ func (c *shardingClient) Start() error { c.rpcClient = rpcClient c.client = ethclient.NewClient(rpcClient) - // Check account existence and unlock account before starting collator client + // Check account existence and unlock account before starting notary client accounts := c.keystore.Accounts() if len(accounts) == 0 { return fmt.Errorf("no accounts found") diff --git a/sharding/collator/collator.go b/sharding/collator/collator.go index 9f5e00da4..fe82b0f45 100644 --- a/sharding/collator/collator.go +++ b/sharding/collator/collator.go @@ -1,4 +1,4 @@ -package collator +package notary import ( "context" @@ -14,7 +14,7 @@ import ( ) // SubscribeBlockHeaders checks incoming block headers and determines if -// we are an eligible collator for collations. Then, it finds the pending tx's +// we are an eligible notary for collations. Then, it finds the pending tx's // from the running geth node and sorts them by descending order of gas price, // eliminates those that ask for too much gas, and routes them over // to the SMC to create a collation @@ -31,17 +31,17 @@ func subscribeBlockHeaders(c client.Client) error { for { // TODO: Error handling for getting disconnected from the client head := <-headerChan - // Query the current state to see if we are an eligible collator + // Query the current state to see if we are an eligible notary log.Info(fmt.Sprintf("Received new header: %v", head.Number.String())) - // Check if we are in the collator pool before checking if we are an eligible collator - v, err := isAccountInCollatorPool(c) + // Check if we are in the notary pool before checking if we are an eligible notary + v, err := isAccountInNotaryPool(c) if err != nil { - return fmt.Errorf("unable to verify client in collator pool. %v", err) + return fmt.Errorf("unable to verify client in notary pool. %v", err) } if v { - if err := checkSMCForCollator(c, head); err != nil { + if err := checkSMCForNotary(c, head); err != nil { return fmt.Errorf("unable to watch shards. %v", err) } } else { @@ -50,16 +50,16 @@ func subscribeBlockHeaders(c client.Client) error { } } -// checkSMCForCollator checks if we are an eligible collator for +// checkSMCForNotary checks if we are an eligible notary for // collation for the available shards in the SMC. The function calls -// getEligibleCollator from the SMC and collator a collation if +// getEligibleNotary from the SMC and notary a collation if // conditions are met -func checkSMCForCollator(c client.Client, head *types.Header) error { - log.Info("Checking if we are an eligible collation collator for a shard...") +func checkSMCForNotary(c client.Client, head *types.Header) error { + log.Info("Checking if we are an eligible collation notary for a shard...") period := big.NewInt(0).Div(head.Number, big.NewInt(sharding.PeriodLength)) for s := int64(0); s < sharding.ShardCount; s++ { - // Checks if we are an eligible collator according to the SMC - addr, err := c.SMCCaller().GetEligibleCollator(&bind.CallOpts{}, big.NewInt(s), period) + // Checks if we are an eligible notary according to the SMC + addr, err := c.SMCCaller().GetEligibleNotary(&bind.CallOpts{}, big.NewInt(s), period) if err != nil { return err @@ -67,7 +67,7 @@ func checkSMCForCollator(c client.Client, head *types.Header) error { // If output is non-empty and the addr == coinbase if addr == c.Account().Address { - log.Info(fmt.Sprintf("Selected as collator on shard: %d", s)) + log.Info(fmt.Sprintf("Selected as notary on shard: %d", s)) err := submitCollation(s) if err != nil { return fmt.Errorf("could not add collation. %v", err) @@ -78,16 +78,16 @@ func checkSMCForCollator(c client.Client, head *types.Header) error { return nil } -// isAccountInCollatorPool checks if the client is in the collator pool because +// isAccountInNotaryPool checks if the client is in the notary pool because // we can't guarantee our tx for deposit will be in the next block header we receive. -// The function calls IsCollatorDeposited from the SMC and returns true if -// the client is in the collator pool -func isAccountInCollatorPool(c client.Client) (bool, error) { +// The function calls IsNotaryDeposited from the SMC and returns true if +// the client is in the notary pool +func isAccountInNotaryPool(c client.Client) (bool, error) { account := c.Account() // Checks if our deposit has gone through according to the SMC - b, err := c.SMCCaller().IsCollatorDeposited(&bind.CallOpts{}, account.Address) + b, err := c.SMCCaller().IsNotaryDeposited(&bind.CallOpts{}, account.Address) if !b && err != nil { - log.Warn(fmt.Sprintf("Account %s not in collator pool.", account.Address.String())) + log.Warn(fmt.Sprintf("Account %s not in notary pool.", account.Address.String())) } return b, err } @@ -122,11 +122,11 @@ func submitCollation(shardID int64) error { return nil } -// joinCollatorPool checks if the account is a collator in the SMC. If +// joinNotaryPool checks if the account is a notary in the SMC. If // the account is not in the set, it will deposit ETH into contract. -func joinCollatorPool(c client.Client) error { +func joinNotaryPool(c client.Client) error { - log.Info("Joining collator pool") + log.Info("Joining notary pool") txOps, err := c.CreateTXOpts(sharding.NotaryDeposit) if err != nil { return fmt.Errorf("unable to intiate the deposit transaction: %v", err) @@ -134,7 +134,7 @@ func joinCollatorPool(c client.Client) error { tx, err := c.SMCTransactor().Deposit(txOps) if err != nil { - return fmt.Errorf("unable to deposit eth and become a collator: %v", err) + return fmt.Errorf("unable to deposit eth and become a notary: %v", err) } log.Info(fmt.Sprintf("Deposited %dETH into contract with transaction hash: %s", new(big.Int).Div(sharding.NotaryDeposit, big.NewInt(params.Ether)), tx.Hash().String())) diff --git a/sharding/collator/collator_client.go b/sharding/collator/collator_client.go index 49373b5ff..56be4804b 100644 --- a/sharding/collator/collator_client.go +++ b/sharding/collator/collator_client.go @@ -1,5 +1,5 @@ -// Package collator holds all of the functionality to run as a collator in a sharded system. -package collator +// Package notary holds all of the functionality to run as a notary in a sharded system. +package notary import ( "github.com/ethereum/go-ethereum/log" @@ -7,33 +7,33 @@ import ( cli "gopkg.in/urfave/cli.v1" ) -// Collator runnable client. -type Collator interface { - // Start the main routine for a collator. +// Notary runnable client. +type Notary interface { + // Start the main routine for a notary. Start() error } -type collator struct { +type notary struct { client client.Client } -// NewCollator creates a new collator instance. -func NewCollator(ctx *cli.Context) Collator { - return &collator{ +// NewNotary creates a new notary instance. +func NewNotary(ctx *cli.Context) Notary { + return ¬ary{ client: client.NewClient(ctx), } } -// Start the main routine for a collator. -func (c *collator) Start() error { - log.Info("Starting collator client") +// Start the main routine for a notary. +func (c *notary) Start() error { + log.Info("Starting notary client") err := c.client.Start() if err != nil { return err } defer c.client.Close() - if err := joinCollatorPool(c.client); err != nil { + if err := joinNotaryPool(c.client); err != nil { return err } diff --git a/sharding/collator/collator_test.go b/sharding/collator/collator_test.go index 2843607f2..1a1e99b1c 100644 --- a/sharding/collator/collator_test.go +++ b/sharding/collator/collator_test.go @@ -1,4 +1,4 @@ -package collator +package notary import ( "math/big" @@ -20,7 +20,7 @@ var ( accountBalance1001Eth, _ = new(big.Int).SetString("1001000000000000000000", 10) ) -// Mock client for testing collator. Should this go into sharding/client/testing? +// Mock client for testing notary. Should this go into sharding/client/testing? type mockClient struct { smc *contracts.SMC t *testing.T @@ -59,7 +59,7 @@ func (m *mockClient) Close() { } // Helper/setup methods -// TODO: consider moving these to common sharding testing package as the collator and smc tests +// TODO: consider moving these to common sharding testing package as the notary and smc tests // use them. func transactOpts() *bind.TransactOpts { return bind.NewKeyedTransactor(key) @@ -71,60 +71,60 @@ func setup() (*backends.SimulatedBackend, *contracts.SMC) { return backend, smc } -func TestIsAccountInCollatorPool(t *testing.T) { +func TestIsAccountInNotaryPool(t *testing.T) { backend, smc := setup() client := &mockClient{smc: smc, t: t} // address should not be in pool initially - b, err := isAccountInCollatorPool(client) + b, err := isAccountInNotaryPool(client) if err != nil { t.Fatal(err) } if b { - t.Fatal("Account unexpectedly in collator pool") + t.Fatal("Account unexpectedly in notary pool") } txOpts := transactOpts() - // deposit in collator pool, then it should return true + // deposit in notary pool, then it should return true txOpts.Value = sharding.NotaryDeposit if _, err := smc.Deposit(txOpts); err != nil { t.Fatalf("Failed to deposit: %v", err) } backend.Commit() - b, err = isAccountInCollatorPool(client) + b, err = isAccountInNotaryPool(client) if err != nil { t.Fatal(err) } if !b { - t.Fatal("Account not in collator pool when expected to be") + t.Fatal("Account not in notary pool when expected to be") } } -func TestJoinCollatorPool(t *testing.T) { +func TestJoinNotaryPool(t *testing.T) { backend, smc := setup() client := &mockClient{smc, t} - // There should be no collators initially - numCollators, err := smc.NumCollators(&bind.CallOpts{}) + // There should be no notarys initially + numNotaries, err := smc.NumNotaries(&bind.CallOpts{}) if err != nil { t.Fatal(err) } - if big.NewInt(0).Cmp(numCollators) != 0 { - t.Fatalf("Unexpected number of collators. Got %d, wanted 0.", numCollators) + if big.NewInt(0).Cmp(numNotaries) != 0 { + t.Fatalf("Unexpected number of notarys. Got %d, wanted 0.", numNotaries) } - err = joinCollatorPool(client) + err = joinNotaryPool(client) if err != nil { t.Fatal(err) } backend.Commit() - // Now there should be one collator - numCollators, err = smc.NumCollators(&bind.CallOpts{}) + // Now there should be one notary + numNotaries, err = smc.NumNotaries(&bind.CallOpts{}) if err != nil { t.Fatal(err) } - if big.NewInt(1).Cmp(numCollators) != 0 { - t.Fatalf("Unexpected number of collators. Got %d, wanted 1.", numCollators) + if big.NewInt(1).Cmp(numNotaries) != 0 { + t.Fatalf("Unexpected number of notarys. Got %d, wanted 1.", numNotaries) } } From 2732187e64d69a5811a85aae86605185f998f938 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Thu, 26 Apr 2018 15:44:34 -0700 Subject: [PATCH 25/30] sharding: file name changes Former-commit-id: add615ca3874397fc04d935b15d0913dcd2b4e18 [formerly 32f4e81a98e3084c1a9c7d277862a04f541f4cbb] Former-commit-id: 63a1630e1f679a7a341d0194c16c9cf9d11cc342 --- sharding/{collator/collator.go => notary/notary.go} | 0 sharding/{collator/collator_client.go => notary/notary_client.go} | 0 sharding/{collator/collator_test.go => notary/notary_test.go} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename sharding/{collator/collator.go => notary/notary.go} (100%) rename sharding/{collator/collator_client.go => notary/notary_client.go} (100%) rename sharding/{collator/collator_test.go => notary/notary_test.go} (100%) diff --git a/sharding/collator/collator.go b/sharding/notary/notary.go similarity index 100% rename from sharding/collator/collator.go rename to sharding/notary/notary.go diff --git a/sharding/collator/collator_client.go b/sharding/notary/notary_client.go similarity index 100% rename from sharding/collator/collator_client.go rename to sharding/notary/notary_client.go diff --git a/sharding/collator/collator_test.go b/sharding/notary/notary_test.go similarity index 100% rename from sharding/collator/collator_test.go rename to sharding/notary/notary_test.go From f30870668010a7c87ff0ca258191ff8f0bc19d57 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Fri, 27 Apr 2018 14:14:55 -0700 Subject: [PATCH 26/30] sharding: \notarys\notaries Former-commit-id: 7eb970515405983d0d0d8f805fdff5c5a3317f93 [formerly 664a9e0acbccebda143006e8063389884efae880] Former-commit-id: 61c048015002bf92da708f80365dfc38d11671ef --- sharding/notary/notary_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sharding/notary/notary_test.go b/sharding/notary/notary_test.go index 1a1e99b1c..a7a7fc6d8 100644 --- a/sharding/notary/notary_test.go +++ b/sharding/notary/notary_test.go @@ -104,13 +104,13 @@ func TestJoinNotaryPool(t *testing.T) { backend, smc := setup() client := &mockClient{smc, t} - // There should be no notarys initially + // There should be no notary initially numNotaries, err := smc.NumNotaries(&bind.CallOpts{}) if err != nil { t.Fatal(err) } if big.NewInt(0).Cmp(numNotaries) != 0 { - t.Fatalf("Unexpected number of notarys. Got %d, wanted 0.", numNotaries) + t.Fatalf("Unexpected number of notaries. Got %d, wanted 0.", numNotaries) } err = joinNotaryPool(client) @@ -125,6 +125,6 @@ func TestJoinNotaryPool(t *testing.T) { t.Fatal(err) } if big.NewInt(1).Cmp(numNotaries) != 0 { - t.Fatalf("Unexpected number of notarys. Got %d, wanted 1.", numNotaries) + t.Fatalf("Unexpected number of notaries. Got %d, wanted 1.", numNotaries) } } From 84389b219b79263f41def60e54641d074c21c0b8 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Fri, 27 Apr 2018 16:38:24 -0700 Subject: [PATCH 27/30] sharding: fixed return bool for functions in sol Former-commit-id: 33624e189e073aa862f2e33f8fd5ebea919d6368 [formerly c7c40d11c99abd923eeee641866e73ea26d7ca13] Former-commit-id: 7d307bc09f0f46d31be20560879954eb8b2a9215 --- sharding/contracts/sharding_manager.go | 28 ++++++++++----------- sharding/contracts/sharding_manager.sol | 16 +++++------- sharding/contracts/sharding_manager_test.go | 3 ++- 3 files changed, 22 insertions(+), 25 deletions(-) diff --git a/sharding/contracts/sharding_manager.go b/sharding/contracts/sharding_manager.go index b2ea30b58..3d3f07fdc 100644 --- a/sharding/contracts/sharding_manager.go +++ b/sharding/contracts/sharding_manager.go @@ -16,10 +16,10 @@ import ( ) // SMCABI is the input ABI used to generate the binding from. -const SMCABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationTrees\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deregisterNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"periodHead\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"registerNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"notaryRegistry\",\"outputs\":[{\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"},{\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"name\":\"deposited\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"releaseNotary\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"notaryPool\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"getNotaryInCommittee\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"uint256\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"addHeader\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"computeHeaderHash\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationHeaders\",\"outputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"notaryPoolLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"shardId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"period\",\"type\":\"int128\"},{\"indexed\":false,\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"HeaderAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryRegistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"}],\"name\":\"NotaryDeregistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryReleased\",\"type\":\"event\"}]" +const SMCABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationTrees\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deregisterNotary\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"name\":\"periodHead\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"registerNotary\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"notaryRegistry\",\"outputs\":[{\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"},{\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"name\":\"deposited\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"releaseNotary\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"notaryPool\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"getNotaryInCommittee\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_shardId\",\"type\":\"uint256\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"addHeader\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"parentHash\",\"type\":\"bytes32\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"computeHeaderHash\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"int256\"},{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"collationHeaders\",\"outputs\":[{\"name\":\"shardId\",\"type\":\"uint256\"},{\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"name\":\"period\",\"type\":\"uint256\"},{\"name\":\"proposerAddress\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"notaryPoolLength\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"shardId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"chunkRoot\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"period\",\"type\":\"int128\"},{\"indexed\":false,\"name\":\"proposerAddress\",\"type\":\"address\"}],\"name\":\"HeaderAdded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryRegistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"deregisteredPeriod\",\"type\":\"uint256\"}],\"name\":\"NotaryDeregistered\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"notary\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"poolIndex\",\"type\":\"uint256\"}],\"name\":\"NotaryReleased\",\"type\":\"event\"}]" // SMCBin is the compiled bytecode used for deploying new contracts. -const SMCBin = `0x608060405234801561001057600080fd5b50610928806100206000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166303dde97781146100be57806358377bd1146100eb578063584475db1461011457806368e9513e1461012c5780636bdd3271146101345780639910851d14610175578063a81f45101461018a578063b09f427e146101be578063b8bc055f146101d9578063b9505ea414610203578063b9d8ef9614610230578063f6f67d361461027a575b600080fd5b3480156100ca57600080fd5b506100d960043560243561028f565b60408051918252519081900360200190f35b3480156100f757600080fd5b506101006102ac565b604080519115158252519081900360200190f35b34801561012057600080fd5b506100d96004356103df565b6101006103f1565b34801561014057600080fd5b50610155600160a060020a03600435166105af565b604080519384526020840192909252151582820152519081900360600190f35b34801561018157600080fd5b506101006105d2565b34801561019657600080fd5b506101a2600435610705565b60408051600160a060020a039092168252519081900360200190f35b3480156101ca57600080fd5b506101a260043560243561072d565b3480156101e557600080fd5b50610100600435602435604435600160a060020a03606435166107c2565b34801561020f57600080fd5b506100d9600435602435604435606435600160a060020a03608435166107cc565b34801561023c57600080fd5b5061024b6004356024356107d7565b60408051948552602085019390935283830191909152600160a060020a03166060830152519081900360800190f35b34801561028657600080fd5b506100d9610811565b600260209081526000928352604080842090915290825290205481565b33600160a060020a0381166000908152600160208190526040822090810154600290910154919291839060ff1615156102e457600080fd5b82600160a060020a03166000838154811015156102fd57fe5b600091825260209091200154600160a060020a03161461031c57600080fd5b610324610817565b5050600160a060020a0382166000908152600160205260409020600543049081905561034f82610846565b600080548390811061035d57fe5b600091825260209182902001805473ffffffffffffffffffffffffffffffffffffffff191690556005805460001901905560408051600160a060020a0386168152918201849052818101839052517f90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a759181900360600190a16001935050505090565b600b6020526000908152604090205481565b33600160a060020a038116600090815260016020526040812060020154909190829060ff161561042057600080fd5b34683635c9adc5dea000001461043557600080fd5b61043d610817565b506104466108b7565b156104a95750600554600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0384161790556104f2565b6104b16108be565b9050816000828154811015156104c357fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a031602179055505b6005805460019081019091556040805160608101825260008082526020808301868152838501868152600160a060020a0389168452918690529390912091518255915192810192909255516002909101805460ff1916911515919091179055600954811061056257600181016009555b60408051600160a060020a03841681526020810183905281517fa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7929181900390910190a160019250505090565b600160208190526000918252604090912080549181015460029091015460ff1683565b33600160a060020a0381166000908152600160208190526040822080820154600290910154929392909160ff90911615151461060d57600080fd5b600160a060020a038216600090815260016020526040902054151561063157600080fd5b600160a060020a038216600090815260016020526040902054613f0001600543041161065c57600080fd5b600160a060020a03821660008181526001602081905260408083208381559182018390556002909101805460ff1916905551683635c9adc5dea000009082818181858883f193505050501580156106b7573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517faee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680929181900390910190a160019250505090565b600080548290811061071357fe5b600091825260209091200154600160a060020a0316905081565b60008080808080600543049450600a5485111561074e576009549350610754565b60085493505b6040805160001960058802018040808352602083018b90528284018c9052925191829003606001909120909450909250849081151561078f57fe5b0690506000818154811015156107a157fe5b600091825260209091200154600160a060020a031698975050505050505050565b6000949350505050565b600095945050505050565b60036020818152600093845260408085209091529183529120805460018201546002830154929093015490929190600160a060020a031684565b60055481565b600a5460009060054304908110156108325760009150610842565b600954600855600a819055600191505b5090565b600754600654141561088c57600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f018190556108ab565b80600660075481548110151561089e57fe5b6000918252602090912001555b50600780546001019055565b6007541590565b600060016007541115156108d157600080fd5b6007805460001901908190556006805490919081106108ec57fe5b90600052602060002001549050905600a165627a7a72305820d453a229f7690048c16d8e76567fa0295b766cfeb78ef0750763de17190630300029` +const SMCBin = `0x608060405234801561001057600080fd5b506108ec806100206000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166303dde97781146100be57806358377bd1146100eb578063584475db1461010257806368e9513e1461011a5780636bdd3271146101225780639910851d14610163578063a81f451014610178578063b09f427e146101ac578063b8bc055f146101c7578063b9505ea4146101f1578063b9d8ef961461021e578063f6f67d3614610268575b600080fd5b3480156100ca57600080fd5b506100d960043560243561027d565b60408051918252519081900360200190f35b3480156100f757600080fd5b5061010061029a565b005b34801561010e57600080fd5b506100d96004356103c5565b6101006103d7565b34801561012e57600080fd5b50610143600160a060020a036004351661058a565b604080519384526020840192909252151582820152519081900360600190f35b34801561016f57600080fd5b506101006105ad565b34801561018457600080fd5b506101906004356106d9565b60408051600160a060020a039092168252519081900360200190f35b3480156101b857600080fd5b50610190600435602435610701565b3480156101d357600080fd5b50610100600435602435604435600160a060020a0360643516610796565b3480156101fd57600080fd5b506100d9600435602435604435606435600160a060020a036084351661079c565b34801561022a57600080fd5b506102396004356024356107a7565b60408051948552602085019390935283830191909152600160a060020a03166060830152519081900360800190f35b34801561027457600080fd5b506100d96107e1565b600260209081526000928352604080842090915290825290205481565b33600160a060020a038116600090815260016020819052604082209081015460029091015490919060ff1615156102d057600080fd5b82600160a060020a03166000838154811015156102e957fe5b600091825260209091200154600160a060020a03161461030857600080fd5b6103106107e7565b50600160a060020a0382166000908152600160205260409020600543049081905561033a8261080a565b600080548390811061034857fe5b600091825260209182902001805473ffffffffffffffffffffffffffffffffffffffff191690556005805460001901905560408051600160a060020a0386168152918201849052818101839052517f90e5afdc8fd31453dcf6e37154fa117ddf3b0324c96c65015563df9d5e4b5a759181900360600190a1505050565b600b6020526000908152604090205481565b33600160a060020a03811660009081526001602052604081206002015460ff161561040157600080fd5b34683635c9adc5dea000001461041657600080fd5b61041e6107e7565b61042661087b565b156104895750600554600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0384161790556104d2565b610491610882565b9050816000828154811015156104a357fe5b9060005260206000200160006101000a815481600160a060020a030219169083600160a060020a031602179055505b6005805460019081019091556040805160608101825260008082526020808301868152838501868152600160a060020a0389168452918690529390912091518255915192810192909255516002909101805460ff1916911515919091179055600954811061054257600181016009555b60408051600160a060020a03841681526020810183905281517fa4fe15c53db34d35a5117acc26c27a2653dc68e2dadfc21ed211e38b7864d7a7929181900390910190a15050565b600160208190526000918252604090912080549181015460029091015460ff1683565b33600160a060020a038116600090815260016020819052604090912080820154600290910154909160ff9091161515146105e657600080fd5b600160a060020a038216600090815260016020526040902054151561060a57600080fd5b600160a060020a038216600090815260016020526040902054613f0001600543041161063557600080fd5b600160a060020a03821660008181526001602081905260408083208381559182018390556002909101805460ff1916905551683635c9adc5dea000009082818181858883f19350505050158015610690573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517faee20171b64b7f3360a142659094ce929970d6963dcea8c34a9bf1ece8033680929181900390910190a15050565b60008054829081106106e757fe5b600091825260209091200154600160a060020a0316905081565b60008080808080600543049450600a54851115610722576009549350610728565b60085493505b6040805160001960058802018040808352602083018b90528284018c9052925191829003606001909120909450909250849081151561076357fe5b06905060008181548110151561077557fe5b600091825260209091200154600160a060020a031698975050505050505050565b50505050565b600095945050505050565b60036020818152600093845260408085209091529183529120805460018201546002830154929093015490929190600160a060020a031684565b60055481565b600a5460054304908110156107fb57610807565b600954600855600a8190555b50565b600754600654141561085057600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0181905561086f565b80600660075481548110151561086257fe5b6000918252602090912001555b50600780546001019055565b6007541590565b6000600160075411151561089557600080fd5b6007805460001901908190556006805490919081106108b057fe5b90600052602060002001549050905600a165627a7a723058206a18c219259d03462104b10265828f09d0a7edbae0d8cc91dad68df76b9ad2820029` // DeploySMC deploys a new Ethereum contract, binding an instance of SMC to it. func DeploySMC(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *SMC, error) { @@ -392,21 +392,21 @@ func (_SMC *SMCCallerSession) PeriodHead(arg0 *big.Int) (*big.Int, error) { // AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns() func (_SMC *SMCTransactor) AddHeader(opts *bind.TransactOpts, _shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { return _SMC.contract.Transact(opts, "addHeader", _shardId, period, chunkRoot, proposerAddress) } // AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns() func (_SMC *SMCSession) AddHeader(_shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, period, chunkRoot, proposerAddress) } // AddHeader is a paid mutator transaction binding the contract method 0xb8bc055f. // -// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns(bool) +// Solidity: function addHeader(_shardId uint256, period uint256, chunkRoot bytes32, proposerAddress address) returns() func (_SMC *SMCTransactorSession) AddHeader(_shardId *big.Int, period *big.Int, chunkRoot [32]byte, proposerAddress common.Address) (*types.Transaction, error) { return _SMC.Contract.AddHeader(&_SMC.TransactOpts, _shardId, period, chunkRoot, proposerAddress) } @@ -434,63 +434,63 @@ func (_SMC *SMCTransactorSession) ComputeHeaderHash(shardId *big.Int, parentHash // DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function deregisterNotary() returns(bool) +// Solidity: function deregisterNotary() returns() func (_SMC *SMCTransactor) DeregisterNotary(opts *bind.TransactOpts) (*types.Transaction, error) { return _SMC.contract.Transact(opts, "deregisterNotary") } // DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function deregisterNotary() returns(bool) +// Solidity: function deregisterNotary() returns() func (_SMC *SMCSession) DeregisterNotary() (*types.Transaction, error) { return _SMC.Contract.DeregisterNotary(&_SMC.TransactOpts) } // DeregisterNotary is a paid mutator transaction binding the contract method 0x58377bd1. // -// Solidity: function deregisterNotary() returns(bool) +// Solidity: function deregisterNotary() returns() func (_SMC *SMCTransactorSession) DeregisterNotary() (*types.Transaction, error) { return _SMC.Contract.DeregisterNotary(&_SMC.TransactOpts) } // RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function registerNotary() returns(bool) +// Solidity: function registerNotary() returns() func (_SMC *SMCTransactor) RegisterNotary(opts *bind.TransactOpts) (*types.Transaction, error) { return _SMC.contract.Transact(opts, "registerNotary") } // RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function registerNotary() returns(bool) +// Solidity: function registerNotary() returns() func (_SMC *SMCSession) RegisterNotary() (*types.Transaction, error) { return _SMC.Contract.RegisterNotary(&_SMC.TransactOpts) } // RegisterNotary is a paid mutator transaction binding the contract method 0x68e9513e. // -// Solidity: function registerNotary() returns(bool) +// Solidity: function registerNotary() returns() func (_SMC *SMCTransactorSession) RegisterNotary() (*types.Transaction, error) { return _SMC.Contract.RegisterNotary(&_SMC.TransactOpts) } // ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function releaseNotary() returns(bool) +// Solidity: function releaseNotary() returns() func (_SMC *SMCTransactor) ReleaseNotary(opts *bind.TransactOpts) (*types.Transaction, error) { return _SMC.contract.Transact(opts, "releaseNotary") } // ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function releaseNotary() returns(bool) +// Solidity: function releaseNotary() returns() func (_SMC *SMCSession) ReleaseNotary() (*types.Transaction, error) { return _SMC.Contract.ReleaseNotary(&_SMC.TransactOpts) } // ReleaseNotary is a paid mutator transaction binding the contract method 0x9910851d. // -// Solidity: function releaseNotary() returns(bool) +// Solidity: function releaseNotary() returns() func (_SMC *SMCTransactorSession) ReleaseNotary() (*types.Transaction, error) { return _SMC.Contract.ReleaseNotary(&_SMC.TransactOpts) } diff --git a/sharding/contracts/sharding_manager.sol b/sharding/contracts/sharding_manager.sol index 0524877ef..5106c1d77 100644 --- a/sharding/contracts/sharding_manager.sol +++ b/sharding/contracts/sharding_manager.sol @@ -95,7 +95,7 @@ contract SMC { /// Registers notary to notatery registry, locks in the notary deposit, /// and returns true on success - function registerNotary() public payable returns(bool) { + function registerNotary() public payable { address notaryAddress = msg.sender; require(!notaryRegistry[notaryAddress].deposited); require(msg.value == NOTARY_DEPOSIT); @@ -125,13 +125,12 @@ contract SMC { } emit NotaryRegistered(notaryAddress, index); - return true; } /// Deregisters notary from notatery registry, lock up period countdowns down, /// notary may call releaseNotary after lock up period finishses to withdraw deposit, /// and returns true on success - function deregisterNotary() public returns(bool) { + function deregisterNotary() public { address notaryAddress = msg.sender; uint index = notaryRegistry[notaryAddress].poolIndex; require(notaryRegistry[notaryAddress].deposited); @@ -147,12 +146,11 @@ contract SMC { delete notaryPool[index]; --notaryPoolLength; emit NotaryDeregistered(notaryAddress, index, deregisteredPeriod); - return true; } /// Removes an entry from notary registry, returns deposit back to the notary, /// and returns true on success. - function releaseNotary() public returns(bool) { + function releaseNotary() public { address notaryAddress = msg.sender; uint index = notaryRegistry[notaryAddress].poolIndex; require(notaryRegistry[notaryAddress].deposited == true); @@ -162,7 +160,6 @@ contract SMC { delete notaryRegistry[notaryAddress]; notaryAddress.transfer(NOTARY_DEPOSIT); emit NotaryReleased(notaryAddress, index); - return true; } /// Calcuates the hash of the header from the input parameters @@ -184,7 +181,7 @@ contract SMC { uint period, bytes32 chunkRoot, address proposerAddress - ) public returns(bool) { + ) public { /* TODO: Anyone can call this at any time. The first header to get included for a given shard in a given period gets in, @@ -194,14 +191,13 @@ contract SMC { /// To keep track of notary size in between periods, we call updateNotarySampleSize /// before notary registration/deregistration so correct size can be applied next period - function updateNotarySampleSize() internal returns(bool) { + function updateNotarySampleSize() internal { uint currentPeriod = block.number / PERIOD_LENGTH; if (currentPeriod < sampleSizeLastUpdatedPeriod) { - return false; + return; } currentPeriodNotarySampleSize = nextPeriodNotarySampleSize; sampleSizeLastUpdatedPeriod = currentPeriod; - return true; } /// Check if the empty slots stack is empty diff --git a/sharding/contracts/sharding_manager_test.go b/sharding/contracts/sharding_manager_test.go index 8dfa8b7ab..a32896220 100644 --- a/sharding/contracts/sharding_manager_test.go +++ b/sharding/contracts/sharding_manager_test.go @@ -6,6 +6,7 @@ import ( "testing" "context" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" @@ -72,7 +73,7 @@ func TestNotaryRegister(t *testing.T) { backend := backends.NewSimulatedBackend(genesis) _, _, smc, _ := deploySMCContract(backend, notaryPoolPrivKeys[0]) - // Test notary 0 has not registered + // Notary 0 has not registered notary, err := smc.NotaryRegistry(&bind.CallOpts{}, notaryPoolAddr[0]) if err != nil { t.Fatalf("Can't get notary registry info: %v", err) From 66de62a85e83276d6a92cd37aac05db5dc492b52 Mon Sep 17 00:00:00 2001 From: Terence Tsao Date: Fri, 27 Apr 2018 18:10:37 -0700 Subject: [PATCH 28/30] sharding: fixed sharding cmds Former-commit-id: 84365d981a292b44d38468c37367f8c0ed44705d [formerly c0b601ccd621170fce6f2c43ef2a285fd712d272] Former-commit-id: f49352c4985317271d073edec7d0d520c4a56684 --- cmd/geth/shardingcmd.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/geth/shardingcmd.go b/cmd/geth/shardingcmd.go index ca03c7bea..db110de25 100644 --- a/cmd/geth/shardingcmd.go +++ b/cmd/geth/shardingcmd.go @@ -36,7 +36,7 @@ Launches a sharding proposer client that connects to a running geth node and pro ) func notaryClient(ctx *cli.Context) error { - c := notary.NewCollator(ctx) + c := notary.NewNotary(ctx) return c.Start() } From cad5710590906b654f995473b49175baaa3fb234 Mon Sep 17 00:00:00 2001 From: Raul Jordan Date: Wed, 2 May 2018 10:39:08 -0500 Subject: [PATCH 29/30] sharding: fix return type of NewClient in client.go to return interface Former-commit-id: c00c1905d427948185c354651ba223d445ffd801 [formerly 89f4058a8774ac7a996f7f28e1c0f973dd92ef84] Former-commit-id: 1e54ceb3fd9e47864779b4ea132382f0a15aa3eb --- sharding/client/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sharding/client/client.go b/sharding/client/client.go index e9c6824df..5523dd614 100644 --- a/sharding/client/client.go +++ b/sharding/client/client.go @@ -55,7 +55,7 @@ type Client interface { } // NewClient forms a new struct instance -func NewClient(ctx *cli.Context) *shardingClient { +func NewClient(ctx *cli.Context) Client { path := node.DefaultDataDir() if ctx.GlobalIsSet(utils.DataDirFlag.Name) { path = ctx.GlobalString(utils.DataDirFlag.Name) From 9a259f7f48f9f7881b213fbdc871516104149b6e Mon Sep 17 00:00:00 2001 From: Raul Jordan Date: Wed, 2 May 2018 11:39:07 -0500 Subject: [PATCH 30/30] sharding: added missing comment Former-commit-id: 4b3a87bae0997905cf7ef4085094356bb8c53c1f [formerly d0eafdcffbdc0fa18af281dadb13b8a7745b5f72] Former-commit-id: 6a7e0a5328eecbdbbd61005a3b73ab297e5fa2f0 --- sharding/client/client.go | 1 + 1 file changed, 1 insertion(+) diff --git a/sharding/client/client.go b/sharding/client/client.go index 5523dd614..eb584feba 100644 --- a/sharding/client/client.go +++ b/sharding/client/client.go @@ -185,6 +185,7 @@ func (c *shardingClient) SMCCaller() *contracts.SMCCaller { return &c.smc.SMCCaller } +// SMCTransactor allows us to send tx's to the SMC programmatically func (c *shardingClient) SMCTransactor() *contracts.SMCTransactor { return &c.smc.SMCTransactor }