/// <summary> /// 共识状态重置,准备发起新一轮共识 /// </summary> /// <param name="wallet">钱包</param> public void Reset(Wallet wallet) { State = ConsensusState.Initial; // 共识状态为 Initial PrevHash = Blockchain.Default.CurrentBlockHash; // 获取上一个区块 BlockIndex = Blockchain.Default.Height + 1; // 新区块下标 ViewNumber = 0; // 初始状态 视图编号为0 Validators = Blockchain.Default.GetValidators(); // 获取议员信息 MyIndex = -1; // 当前议员下标初始化 PrimaryIndex = BlockIndex % (uint)Validators.Length; // 确定议长 p = (h - v)mod n 此处 v = 0 TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length];// 用于保存众议员当前视图编号 KeyPair = null; for (int i = 0; i < Validators.Length; i++) { // 获取自己的议员编号以及密钥 WalletAccount account = wallet.GetAccount(Validators[i]); if (account?.HasKey == true) { MyIndex = i; KeyPair = account.GetKey(); break; } } _header = null; }
public void Reset(Wallet wallet, Blockchain blockchain) { Snapshot?.Dispose(); Snapshot = blockchain.GetSnapshot(); State = ConsensusState.Initial; PrevHash = Snapshot.CurrentBlockHash; BlockIndex = Snapshot.Height + 1; ViewNumber = 0; Validators = Snapshot.GetValidators(); MyIndex = -1; PrimaryIndex = BlockIndex % (uint)Validators.Length; TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length]; KeyPair = null; ChainHash = blockchain.ChainHash; for (int i = 0; i < Validators.Length; i++) { WalletAccount account = wallet.GetAccount(Validators[i]); if (account?.HasKey == true) { MyIndex = i; KeyPair = account.GetKey(); break; } } _header = null; }
public void ChangeView(byte view_number) { ReportNeoBlockchain reportObj = new ReportNeoBlockchain("[NeoConsensusContext-ChangeView]"); Console.WriteLine("Test inside Consensus ChangeView"); DateTime?d1 = DateTime.Now; int p = ((int)BlockIndex - view_number) % Validators.Length; State &= ConsensusState.SignatureSent; ViewNumber = view_number; PrimaryIndex = p >= 0 ? (uint)p : (uint)(p + Validators.Length); if (State == ConsensusState.Initial) { TransactionHashes = null; Signatures = new byte[Validators.Length][]; } _header = null; //TimeSpan diff = DateTime.Now - PreviousDateTime; //double seconds = diff.TotalSeconds; //Console.WriteLine("Elapsed seconds are:"+seconds); DateTime?d2 = DateTime.Now.AddDays(-1); Console.WriteLine("Elapsed seconds are:" + (double)(d1 - d2).GetValueOrDefault().TotalSeconds); reportObj.appendElapsedTime(); }
public ConsensusState GetConsensusState() { var raw = _state.Get(EntryPrefix.ConsensusState.BuildPrefix()) ?? throw new ConsensusStateNotPresentException(); return(ConsensusState.FromBytes(raw)); }
public void Reset(Wallet wallet) { State = ConsensusState.Initial; PrevHash = Blockchain.Default.CurrentBlockHash; BlockIndex = Blockchain.Default.Height + 1; ViewNumber = 0; Validators = Blockchain.Default.GetValidators(); MyIndex = -1; PrimaryIndex = BlockIndex % (uint)Validators.Length; TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length]; KeyPair = null; for (int i = 0; i < Validators.Length; i++) { var account = wallet.GetAccount(Validators[i]); if (account?.HasKey != true) { continue; } MyIndex = i; KeyPair = account.GetKey(); break; } _header = null; }
public void ChangeView(byte view_number) { int p = ((int)Height - view_number) % Miners.Length; State = ConsensusState.Initial; ViewNumber = view_number; PrimaryIndex = p >= 0 ? (uint)p : (uint)(p + Miners.Length); TransactionHashes = null; Signatures = new byte[Miners.Length][]; _header = null; }
public void UpdateValidators( IEnumerable <ECDSAPublicKey> ecdsaKeys, PublicKeySet tsKeys, PublicKey tpkePublicKey ) { var state = new ConsensusState( tpkePublicKey.ToBytes(), ecdsaKeys .Zip(tsKeys.Keys, (ecdsaKey, tsKey) => new ValidatorCredentials(ecdsaKey, tsKey.ToBytes())) .ToArray() ); SetConsensusState(state); }
public void ChangeView(byte view_number) { int p = ((int)BlockIndex - view_number) % Validators.Length; State &= ConsensusState.SignatureSent; ViewNumber = view_number; PrimaryIndex = p >= 0 ? (uint)p : (uint)(p + Validators.Length); if (State == ConsensusState.Initial) { TransactionHashes = null; Signatures = new byte[Validators.Length][]; } _header = null; }
public void ChangeView(byte view_number) { State &= ConsensusState.SignatureSent; ViewNumber = view_number; PrimaryIndex = GetPrimaryIndex(view_number); if (State == ConsensusState.Initial) { TransactionHashes = null; Signatures = new byte[Validators.Length][]; } if (MyIndex >= 0) { ExpectedView[MyIndex] = view_number; } _header = null; }
public void Reset(Wallet wallet) { State = ConsensusState.Initial; PrevHash = Blockchain.Default.CurrentBlockHash; BlockIndex = Blockchain.Default.Height + 1; ViewNumber = 0; Validators = Blockchain.Default.GetValidators(); MyIndex = -1; PrimaryIndex = BlockIndex % (uint)Validators.Length; TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length]; for (int i = 0; i < Validators.Length; i++) { if (wallet.ContainsKey(Validators[i])) { MyIndex = i; break; } } _header = null; }
public void Reset(Wallet wallet) { State = ConsensusState.Initial; PrevHash = Blockchain.Default.CurrentBlockHash; BlockIndex = Blockchain.Default.Height + 1; ViewNumber = 0; Validators = Blockchain.Default.GetValidators(); MyIndex = -1; PrimaryIndex = BlockIndex % (uint)Validators.Length; TransactionHashes = null; Signatures = new byte[Validators.Length][]; ExpectedView = new byte[Validators.Length]; KeyPair = null; WalletAccount account = wallet.GetAccount(Blockchain.GetConsensusAddress(Validators)); if (account?.HasKey == true) { KeyPair = account.GetKey(); MyIndex = Array.IndexOf(Validators, KeyPair.PublicKey); } _header = null; }
public void Reset(Wallet wallet) { State = ConsensusState.Initial; PrevHash = Blockchain.Default.CurrentBlockHash; Height = Blockchain.Default.Height + 1; ViewNumber = 0; Miners = Blockchain.Default.GetMiners(); MinerIndex = -1; PrimaryIndex = Height % (uint)Miners.Length; TransactionHashes = null; Signatures = new byte[Miners.Length][]; ExpectedView = new byte[Miners.Length]; for (int i = 0; i < Miners.Length; i++) { if (wallet.ContainsAccount(Miners[i])) { MinerIndex = i; break; } } _header = null; }
// Every time a node starts, it first tries to build the genesis block public bool TryBuildGenesisBlock() { // genesis block is built from the config.json file // genesis block mints tokens to the validators for the first cycle var genesisBlock = _genesisBuilder.Build(); // if genesis block can already be found, we return immediately if (_stateManager.LastApprovedSnapshot.Blocks.GetBlockByHeight(0) != null) { return(false); } var snapshot = _stateManager.NewSnapshot(); var genesisConfig = _configManager.GetConfig <GenesisConfig>("genesis"); if (genesisConfig is null) { return(false); } genesisConfig.ValidateOrThrow(); var initialConsensusState = new ConsensusState( genesisConfig.ThresholdEncryptionPublicKey.HexToBytes(), genesisConfig.Validators.Select(v => new ValidatorCredentials ( v.EcdsaPublicKey.HexToBytes().ToPublicKey(), v.ThresholdSignaturePublicKey.HexToBytes() )).ToArray() ); snapshot.Validators.SetConsensusState(initialConsensusState); // stake delegation happens even before genesis block // stake delegation means - some other address stakes for the validators // config.json keeps the stakerAddress and the stakeAmount for each of the validators // init system contracts storage var dummyStakerPub = new string('f', CryptoUtils.PublicKeyLength * 2).HexToBytes(); snapshot.Storage.SetRawValue( ContractRegisterer.StakingContract, new BigInteger(6).ToUInt256().Buffer, dummyStakerPub ); // TODO: get rid of explicit numbering of fields var initialVrfSeed = Encoding.ASCII.GetBytes("test"); snapshot.Storage.SetRawValue( ContractRegisterer.StakingContract, new BigInteger(7).ToUInt256().Buffer, initialVrfSeed ); var initialBlockReward = Money.Parse(genesisConfig.BlockReward).ToUInt256().ToBytes(); snapshot.Storage.SetRawValue( ContractRegisterer.GovernanceContract, new BigInteger(3).ToUInt256().Buffer, initialBlockReward ); var initialBasicGasPrice = Money.Parse(genesisConfig.BasicGasPrice).ToUInt256().ToBytes(); snapshot.Storage.SetRawValue( ContractRegisterer.GovernanceContract, new BigInteger(8).ToUInt256().Buffer, initialBasicGasPrice ); // The followings are the variables used in stakingContract // This variables are stored in the storage snapshot and is a part of the chain // To understand the what each variables represent, refer to StakingContract.cs // We do the stake delegation even before the execution of genesis block var _userToStake = new StorageMapping( ContractRegisterer.StakingContract, snapshot.Storage, new BigInteger(3).ToUInt256() ); var _stakers = new StorageVariable( ContractRegisterer.StakingContract, snapshot.Storage, new BigInteger(6).ToUInt256() ); var _userToPubKey = new StorageMapping( ContractRegisterer.StakingContract, snapshot.Storage, new BigInteger(2).ToUInt256() ); var _pubKeyToStaker = new StorageMapping( ContractRegisterer.StakingContract, snapshot.Storage, new BigInteger(12).ToUInt256() ); var _userToStartCycle = new StorageMapping( ContractRegisterer.StakingContract, snapshot.Storage, new BigInteger(4).ToUInt256() ); foreach (var validator in genesisConfig.Validators) { if (validator.StakeAmount == null || validator.StakerAddress == null) { continue; } var validatorPublicKey = validator.EcdsaPublicKey.HexToBytes(); var validatorAddress = Hepler.PublicKeyToAddress(validatorPublicKey).ToBytes(); var stakerAddress = validator.StakerAddress.HexToBytes(); // add balance to staking contract var stakeAmount = Money.Parse(validator.StakeAmount); snapshot.Balances.AddBalance(ContractRegisterer.StakingContract, stakeAmount, true); // set stake value _userToStake.SetValue(validatorAddress, stakeAmount.ToUInt256().ToBytes()); // update stakers list var stakers = _stakers.Get(); _stakers.Set(stakers.Concat(validatorPublicKey).ToArray()); // user to public key and public key to staker _userToPubKey.SetValue(validatorAddress, validatorPublicKey); _pubKeyToStaker.SetValue(validatorPublicKey, stakerAddress); // set start cycle _userToStartCycle.SetValue(validatorAddress, BitConverter.GetBytes(0)); } _stateManager.Approve(); // emulate and execute the genesis block var(error, removeTransactions, stateHash, relayTransactions) = Emulate(genesisBlock.Block, genesisBlock.Transactions); if (error != OperatingError.Ok) { throw new InvalidBlockException(error); } if (removeTransactions.Count != 0) { throw new InvalidBlockException(OperatingError.InvalidTransaction); } if (relayTransactions.Count != 0) { throw new InvalidBlockException(OperatingError.InvalidTransaction); } genesisBlock.Block.Header.StateHash = stateHash; genesisBlock.Block.Hash = genesisBlock.Block.Header.Keccak(); error = Execute(genesisBlock.Block, genesisBlock.Transactions, commit: true, checkStateHash: true); if (error != OperatingError.Ok) { throw new InvalidBlockException(error); } _stateManager.Commit(); BlockPersisted(genesisBlock.Block); return(true); }
public void SetConsensusState(ConsensusState consensusState) { var raw = consensusState.ToBytes(); _state.AddOrUpdate(EntryPrefix.ConsensusState.BuildPrefix(), raw); }