func LoadState(db dbm.DB) *State { s := &State{DB: db} buf := db.Get(stateKey) if len(buf) == 0 { return nil } else { r, n, err := bytes.NewReader(buf), new(int64), new(error) s.ChainID = wire.ReadString(r, n, err) s.LastBlockHeight = wire.ReadVarint(r, n, err) s.LastBlockHash = wire.ReadByteSlice(r, n, err) s.LastBlockParts = wire.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader) s.LastBlockTime = wire.ReadTime(r, n, err) s.BondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) s.LastBondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) s.UnbondingValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) accountsHash := wire.ReadByteSlice(r, n, err) s.accounts = merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db) s.accounts.Load(accountsHash) validatorInfosHash := wire.ReadByteSlice(r, n, err) s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db) s.validatorInfos.Load(validatorInfosHash) nameRegHash := wire.ReadByteSlice(r, n, err) s.nameReg = merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db) s.nameReg.Load(nameRegHash) if *err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED Exit(Fmt("Data has been corrupted or its spec has changed: %v\n", *err)) } // TODO: ensure that buf is completely read. } return s }
// Read a (length prefixed) byteslice then decode the object using the codec func decodeByteSlice(codec wire.Codec, r io.Reader, n *int64, err *error) interface{} { bytez := wire.ReadByteSlice(r, n, err) if *err != nil { return nil } n_ := new(int64) return codec.Decode(bytes.NewBuffer(bytez), n_, err) }
// NOTE: The hash is not saved or set. The caller should set the hash afterwards. // (Presumably the caller already has the hash) func ReadIAVLNode(t *IAVLTree, r io.Reader, n *int64, err *error) *IAVLNode { node := &IAVLNode{} // node header node.height = wire.ReadInt8(r, n, err) node.size = wire.ReadVarint(r, n, err) node.key = decodeByteSlice(t.keyCodec, r, n, err) if node.height == 0 { // value node.value = decodeByteSlice(t.valueCodec, r, n, err) } else { // children node.leftHash = wire.ReadByteSlice(r, n, err) node.rightHash = wire.ReadByteSlice(r, n, err) } return node }