github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/gossip/state/metastate.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package state
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  )
    23  
    24  // NodeMetastate information to store the information about current
    25  // height of the ledger (last accepted block sequence number).
    26  type NodeMetastate struct {
    27  
    28  	// Actual ledger height
    29  	LedgerHeight uint64
    30  }
    31  
    32  // NewNodeMetastate creates new meta data with given ledger height148.69
    33  func NewNodeMetastate(height uint64) *NodeMetastate {
    34  	return &NodeMetastate{height}
    35  }
    36  
    37  // Bytes decodes meta state into byte array for serialization
    38  func (n *NodeMetastate) Bytes() ([]byte, error) {
    39  	buffer := new(bytes.Buffer)
    40  	// Explicitly specify byte order for write into the buffer
    41  	// to provide cross platform support, note the it consistent
    42  	// with FromBytes function
    43  	err := binary.Write(buffer, binary.BigEndian, *n)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	return buffer.Bytes(), nil
    48  }
    49  
    50  // Height returns ledger height from the state
    51  func (n *NodeMetastate) Height() uint64 {
    52  	return n.LedgerHeight
    53  }
    54  
    55  // Update state with new ledger height
    56  func (n *NodeMetastate) Update(height uint64) {
    57  	n.LedgerHeight = height
    58  }
    59  
    60  // FromBytes - encode from byte array into meta data structure
    61  func FromBytes(buf []byte) (*NodeMetastate, error) {
    62  	state := NodeMetastate{}
    63  	reader := bytes.NewReader(buf)
    64  	// As bytes are written in the big endian to keep supporting
    65  	// cross platforming and for consistency reasons read also
    66  	// done using same order
    67  	err := binary.Read(reader, binary.BigEndian, &state)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	return &state, nil
    72  }