gitee.com/aqchain/go-ethereum@v0.0.9/bmt/bmt.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package bmt provides a binary merkle tree implementation
    18  package bmt
    19  
    20  import (
    21  	"fmt"
    22  	"hash"
    23  	"io"
    24  	"strings"
    25  	"sync"
    26  	"sync/atomic"
    27  )
    28  
    29  /*
    30  Binary Merkle Tree Hash is a hash function over arbitrary datachunks of limited size
    31  It is defined as the root hash of the binary merkle tree built over fixed size segments
    32  of the underlying chunk using any base hash function (e.g keccak 256 SHA3)
    33  
    34  It is used as the chunk hash function in swarm which in turn is the basis for the
    35  128 branching swarm hash http://swarm-guide.readthedocs.io/en/latest/architecture.html#swarm-hash
    36  
    37  The BMT is optimal for providing compact inclusion proofs, i.e. prove that a
    38  segment is a substring of a chunk starting at a particular offset
    39  The size of the underlying segments is fixed at 32 bytes (called the resolution
    40  of the BMT hash), the EVM word size to optimize for on-chain BMT verification
    41  as well as the hash size optimal for inclusion proofs in the merkle tree of the swarm hash.
    42  
    43  Two implementations are provided:
    44  
    45  * RefHasher is optimized for code simplicity and meant as a reference implementation
    46  * Hasher is optimized for speed taking advantage of concurrency with minimalistic
    47    control structure to coordinate the concurrent routines
    48    It implements the ChunkHash interface as well as the go standard hash.Hash interface
    49  
    50  */
    51  
    52  const (
    53  	// DefaultSegmentCount is the maximum number of segments of the underlying chunk
    54  	DefaultSegmentCount = 128 // Should be equal to storage.DefaultBranches
    55  	// DefaultPoolSize is the maximum number of bmt trees used by the hashers, i.e,
    56  	// the maximum number of concurrent BMT hashing operations performed by the same hasher
    57  	DefaultPoolSize = 8
    58  )
    59  
    60  // BaseHasher is a hash.Hash constructor function used for the base hash of the  BMT.
    61  type BaseHasher func() hash.Hash
    62  
    63  // Hasher a reusable hasher for fixed maximum size chunks representing a BMT
    64  // implements the hash.Hash interface
    65  // reuse pool of Tree-s for amortised memory allocation and resource control
    66  // supports order-agnostic concurrent segment writes
    67  // as well as sequential read and write
    68  // can not be called concurrently on more than one chunk
    69  // can be further appended after Sum
    70  // Reset gives back the Tree to the pool and guaranteed to leave
    71  // the tree and itself in a state reusable for hashing a new chunk
    72  type Hasher struct {
    73  	pool        *TreePool   // BMT resource pool
    74  	bmt         *Tree       // prebuilt BMT resource for flowcontrol and proofs
    75  	blocksize   int         // segment size (size of hash) also for hash.Hash
    76  	count       int         // segment count
    77  	size        int         // for hash.Hash same as hashsize
    78  	cur         int         // cursor position for rightmost currently open chunk
    79  	segment     []byte      // the rightmost open segment (not complete)
    80  	depth       int         // index of last level
    81  	result      chan []byte // result channel
    82  	hash        []byte      // to record the result
    83  	max         int32       // max segments for SegmentWriter interface
    84  	blockLength []byte      // The block length that needes to be added in Sum
    85  }
    86  
    87  // New creates a reusable Hasher
    88  // implements the hash.Hash interface
    89  // pulls a new Tree from a resource pool for hashing each chunk
    90  func New(p *TreePool) *Hasher {
    91  	return &Hasher{
    92  		pool:      p,
    93  		depth:     depth(p.SegmentCount),
    94  		size:      p.SegmentSize,
    95  		blocksize: p.SegmentSize,
    96  		count:     p.SegmentCount,
    97  		result:    make(chan []byte),
    98  	}
    99  }
   100  
   101  // Node is a reuseable segment hasher representing a node in a BMT
   102  // it allows for continued writes after a Sum
   103  // and is left in completely reusable state after Reset
   104  type Node struct {
   105  	level, index int   // position of node for information/logging only
   106  	initial      bool  // first and last node
   107  	root         bool  // whether the node is root to a smaller BMT
   108  	isLeft       bool  // whether it is left side of the parent double segment
   109  	unbalanced   bool  // indicates if a node has only the left segment
   110  	parent       *Node // BMT connections
   111  	state        int32 // atomic increment impl concurrent boolean toggle
   112  	left, right  []byte
   113  }
   114  
   115  // NewNode constructor for segment hasher nodes in the BMT
   116  func NewNode(level, index int, parent *Node) *Node {
   117  	return &Node{
   118  		parent:  parent,
   119  		level:   level,
   120  		index:   index,
   121  		initial: index == 0,
   122  		isLeft:  index%2 == 0,
   123  	}
   124  }
   125  
   126  // TreePool provides a pool of Trees used as resources by Hasher
   127  // a Tree popped from the pool is guaranteed to have clean state
   128  // for hashing a new chunk
   129  // Hasher Reset releases the Tree to the pool
   130  type TreePool struct {
   131  	lock         sync.Mutex
   132  	c            chan *Tree
   133  	hasher       BaseHasher
   134  	SegmentSize  int
   135  	SegmentCount int
   136  	Capacity     int
   137  	count        int
   138  }
   139  
   140  // NewTreePool creates a Tree pool with hasher, segment size, segment count and capacity
   141  // on GetTree it reuses free Trees or creates a new one if size is not reached
   142  func NewTreePool(hasher BaseHasher, segmentCount, capacity int) *TreePool {
   143  	return &TreePool{
   144  		c:            make(chan *Tree, capacity),
   145  		hasher:       hasher,
   146  		SegmentSize:  hasher().Size(),
   147  		SegmentCount: segmentCount,
   148  		Capacity:     capacity,
   149  	}
   150  }
   151  
   152  // Drain drains the pool until it has no more than n resources
   153  func (p *TreePool) Drain(n int) {
   154  	p.lock.Lock()
   155  	defer p.lock.Unlock()
   156  	for len(p.c) > n {
   157  		<-p.c
   158  		p.count--
   159  	}
   160  }
   161  
   162  // Reserve is blocking until it returns an available Tree
   163  // it reuses free Trees or creates a new one if size is not reached
   164  func (p *TreePool) Reserve() *Tree {
   165  	p.lock.Lock()
   166  	defer p.lock.Unlock()
   167  	var t *Tree
   168  	if p.count == p.Capacity {
   169  		return <-p.c
   170  	}
   171  	select {
   172  	case t = <-p.c:
   173  	default:
   174  		t = NewTree(p.hasher, p.SegmentSize, p.SegmentCount)
   175  		p.count++
   176  	}
   177  	return t
   178  }
   179  
   180  // Release gives back a Tree to the pool.
   181  // This Tree is guaranteed to be in reusable state
   182  // does not need locking
   183  func (p *TreePool) Release(t *Tree) {
   184  	p.c <- t // can never fail but...
   185  }
   186  
   187  // Tree is a reusable control structure representing a BMT
   188  // organised in a binary tree
   189  // Hasher uses a TreePool to pick one for each chunk hash
   190  // the Tree is 'locked' while not in the pool
   191  type Tree struct {
   192  	leaves []*Node
   193  }
   194  
   195  // Draw draws the BMT (badly)
   196  func (t *Tree) Draw(hash []byte, d int) string {
   197  	var left, right []string
   198  	var anc []*Node
   199  	for i, n := range t.leaves {
   200  		left = append(left, fmt.Sprintf("%v", hashstr(n.left)))
   201  		if i%2 == 0 {
   202  			anc = append(anc, n.parent)
   203  		}
   204  		right = append(right, fmt.Sprintf("%v", hashstr(n.right)))
   205  	}
   206  	anc = t.leaves
   207  	var hashes [][]string
   208  	for l := 0; len(anc) > 0; l++ {
   209  		var nodes []*Node
   210  		hash := []string{""}
   211  		for i, n := range anc {
   212  			hash = append(hash, fmt.Sprintf("%v|%v", hashstr(n.left), hashstr(n.right)))
   213  			if i%2 == 0 && n.parent != nil {
   214  				nodes = append(nodes, n.parent)
   215  			}
   216  		}
   217  		hash = append(hash, "")
   218  		hashes = append(hashes, hash)
   219  		anc = nodes
   220  	}
   221  	hashes = append(hashes, []string{"", fmt.Sprintf("%v", hashstr(hash)), ""})
   222  	total := 60
   223  	del := "                             "
   224  	var rows []string
   225  	for i := len(hashes) - 1; i >= 0; i-- {
   226  		var textlen int
   227  		hash := hashes[i]
   228  		for _, s := range hash {
   229  			textlen += len(s)
   230  		}
   231  		if total < textlen {
   232  			total = textlen + len(hash)
   233  		}
   234  		delsize := (total - textlen) / (len(hash) - 1)
   235  		if delsize > len(del) {
   236  			delsize = len(del)
   237  		}
   238  		row := fmt.Sprintf("%v: %v", len(hashes)-i-1, strings.Join(hash, del[:delsize]))
   239  		rows = append(rows, row)
   240  
   241  	}
   242  	rows = append(rows, strings.Join(left, "  "))
   243  	rows = append(rows, strings.Join(right, "  "))
   244  	return strings.Join(rows, "\n") + "\n"
   245  }
   246  
   247  // NewTree initialises the Tree by building up the nodes of a BMT
   248  // segment size is stipulated to be the size of the hash
   249  // segmentCount needs to be positive integer and does not need to be
   250  // a power of two and can even be an odd number
   251  // segmentSize * segmentCount determines the maximum chunk size
   252  // hashed using the tree
   253  func NewTree(hasher BaseHasher, segmentSize, segmentCount int) *Tree {
   254  	n := NewNode(0, 0, nil)
   255  	n.root = true
   256  	prevlevel := []*Node{n}
   257  	// iterate over levels and creates 2^level nodes
   258  	level := 1
   259  	count := 2
   260  	for d := 1; d <= depth(segmentCount); d++ {
   261  		nodes := make([]*Node, count)
   262  		for i := 0; i < len(nodes); i++ {
   263  			parent := prevlevel[i/2]
   264  			t := NewNode(level, i, parent)
   265  			nodes[i] = t
   266  		}
   267  		prevlevel = nodes
   268  		level++
   269  		count *= 2
   270  	}
   271  	// the datanode level is the nodes on the last level where
   272  	return &Tree{
   273  		leaves: prevlevel,
   274  	}
   275  }
   276  
   277  // methods needed by hash.Hash
   278  
   279  // Size returns the size
   280  func (h *Hasher) Size() int {
   281  	return h.size
   282  }
   283  
   284  // BlockSize returns the block size
   285  func (h *Hasher) BlockSize() int {
   286  	return h.blocksize
   287  }
   288  
   289  // Sum returns the hash of the buffer
   290  // hash.Hash interface Sum method appends the byte slice to the underlying
   291  // data before it calculates and returns the hash of the chunk
   292  func (h *Hasher) Sum(b []byte) (r []byte) {
   293  	t := h.bmt
   294  	i := h.cur
   295  	n := t.leaves[i]
   296  	j := i
   297  	// must run strictly before all nodes calculate
   298  	// datanodes are guaranteed to have a parent
   299  	if len(h.segment) > h.size && i > 0 && n.parent != nil {
   300  		n = n.parent
   301  	} else {
   302  		i *= 2
   303  	}
   304  	d := h.finalise(n, i)
   305  	h.writeSegment(j, h.segment, d)
   306  	c := <-h.result
   307  	h.releaseTree()
   308  
   309  	// sha3(length + BMT(pure_chunk))
   310  	if h.blockLength == nil {
   311  		return c
   312  	}
   313  	res := h.pool.hasher()
   314  	res.Reset()
   315  	res.Write(h.blockLength)
   316  	res.Write(c)
   317  	return res.Sum(nil)
   318  }
   319  
   320  // Hasher implements the SwarmHash interface
   321  
   322  // Hash waits for the hasher result and returns it
   323  // caller must call this on a BMT Hasher being written to
   324  func (h *Hasher) Hash() []byte {
   325  	return <-h.result
   326  }
   327  
   328  // Hasher implements the io.Writer interface
   329  
   330  // Write fills the buffer to hash
   331  // with every full segment complete launches a hasher go routine
   332  // that shoots up the BMT
   333  func (h *Hasher) Write(b []byte) (int, error) {
   334  	l := len(b)
   335  	if l <= 0 {
   336  		return 0, nil
   337  	}
   338  	s := h.segment
   339  	i := h.cur
   340  	count := (h.count + 1) / 2
   341  	need := h.count*h.size - h.cur*2*h.size
   342  	size := h.size
   343  	if need > size {
   344  		size *= 2
   345  	}
   346  	if l < need {
   347  		need = l
   348  	}
   349  	// calculate missing bit to complete current open segment
   350  	rest := size - len(s)
   351  	if need < rest {
   352  		rest = need
   353  	}
   354  	s = append(s, b[:rest]...)
   355  	need -= rest
   356  	// read full segments and the last possibly partial segment
   357  	for need > 0 && i < count-1 {
   358  		// push all finished chunks we read
   359  		h.writeSegment(i, s, h.depth)
   360  		need -= size
   361  		if need < 0 {
   362  			size += need
   363  		}
   364  		s = b[rest : rest+size]
   365  		rest += size
   366  		i++
   367  	}
   368  	h.segment = s
   369  	h.cur = i
   370  	// otherwise, we can assume len(s) == 0, so all buffer is read and chunk is not yet full
   371  	return l, nil
   372  }
   373  
   374  // Hasher implements the io.ReaderFrom interface
   375  
   376  // ReadFrom reads from io.Reader and appends to the data to hash using Write
   377  // it reads so that chunk to hash is maximum length or reader reaches EOF
   378  // caller must Reset the hasher prior to call
   379  func (h *Hasher) ReadFrom(r io.Reader) (m int64, err error) {
   380  	bufsize := h.size*h.count - h.size*h.cur - len(h.segment)
   381  	buf := make([]byte, bufsize)
   382  	var read int
   383  	for {
   384  		var n int
   385  		n, err = r.Read(buf)
   386  		read += n
   387  		if err == io.EOF || read == len(buf) {
   388  			hash := h.Sum(buf[:n])
   389  			if read == len(buf) {
   390  				err = NewEOC(hash)
   391  			}
   392  			break
   393  		}
   394  		if err != nil {
   395  			break
   396  		}
   397  		n, err = h.Write(buf[:n])
   398  		if err != nil {
   399  			break
   400  		}
   401  	}
   402  	return int64(read), err
   403  }
   404  
   405  // Reset needs to be called before writing to the hasher
   406  func (h *Hasher) Reset() {
   407  	h.getTree()
   408  	h.blockLength = nil
   409  }
   410  
   411  // Hasher implements the SwarmHash interface
   412  
   413  // ResetWithLength needs to be called before writing to the hasher
   414  // the argument is supposed to be the byte slice binary representation of
   415  // the length of the data subsumed under the hash
   416  func (h *Hasher) ResetWithLength(l []byte) {
   417  	h.Reset()
   418  	h.blockLength = l
   419  }
   420  
   421  // Release gives back the Tree to the pool whereby it unlocks
   422  // it resets tree, segment and index
   423  func (h *Hasher) releaseTree() {
   424  	if h.bmt != nil {
   425  		n := h.bmt.leaves[h.cur]
   426  		for ; n != nil; n = n.parent {
   427  			n.unbalanced = false
   428  			if n.parent != nil {
   429  				n.root = false
   430  			}
   431  		}
   432  		h.pool.Release(h.bmt)
   433  		h.bmt = nil
   434  
   435  	}
   436  	h.cur = 0
   437  	h.segment = nil
   438  }
   439  
   440  func (h *Hasher) writeSegment(i int, s []byte, d int) {
   441  	hash := h.pool.hasher()
   442  	n := h.bmt.leaves[i]
   443  
   444  	if len(s) > h.size && n.parent != nil {
   445  		go func() {
   446  			hash.Reset()
   447  			hash.Write(s)
   448  			s = hash.Sum(nil)
   449  
   450  			if n.root {
   451  				h.result <- s
   452  				return
   453  			}
   454  			h.run(n.parent, hash, d, n.index, s)
   455  		}()
   456  		return
   457  	}
   458  	go h.run(n, hash, d, i*2, s)
   459  }
   460  
   461  func (h *Hasher) run(n *Node, hash hash.Hash, d int, i int, s []byte) {
   462  	isLeft := i%2 == 0
   463  	for {
   464  		if isLeft {
   465  			n.left = s
   466  		} else {
   467  			n.right = s
   468  		}
   469  		if !n.unbalanced && n.toggle() {
   470  			return
   471  		}
   472  		if !n.unbalanced || !isLeft || i == 0 && d == 0 {
   473  			hash.Reset()
   474  			hash.Write(n.left)
   475  			hash.Write(n.right)
   476  			s = hash.Sum(nil)
   477  
   478  		} else {
   479  			s = append(n.left, n.right...)
   480  		}
   481  
   482  		h.hash = s
   483  		if n.root {
   484  			h.result <- s
   485  			return
   486  		}
   487  
   488  		isLeft = n.isLeft
   489  		n = n.parent
   490  		i++
   491  	}
   492  }
   493  
   494  // getTree obtains a BMT resource by reserving one from the pool
   495  func (h *Hasher) getTree() *Tree {
   496  	if h.bmt != nil {
   497  		return h.bmt
   498  	}
   499  	t := h.pool.Reserve()
   500  	h.bmt = t
   501  	return t
   502  }
   503  
   504  // atomic bool toggle implementing a concurrent reusable 2-state object
   505  // atomic addint with %2 implements atomic bool toggle
   506  // it returns true if the toggler just put it in the active/waiting state
   507  func (n *Node) toggle() bool {
   508  	return atomic.AddInt32(&n.state, 1)%2 == 1
   509  }
   510  
   511  func hashstr(b []byte) string {
   512  	end := len(b)
   513  	if end > 4 {
   514  		end = 4
   515  	}
   516  	return fmt.Sprintf("%x", b[:end])
   517  }
   518  
   519  func depth(n int) (d int) {
   520  	for l := (n - 1) / 2; l > 0; l /= 2 {
   521  		d++
   522  	}
   523  	return d
   524  }
   525  
   526  // finalise is following the zigzags on the tree belonging
   527  // to the final datasegment
   528  func (h *Hasher) finalise(n *Node, i int) (d int) {
   529  	isLeft := i%2 == 0
   530  	for {
   531  		// when the final segment's path is going via left segments
   532  		// the incoming data is pushed to the parent upon pulling the left
   533  		// we do not need toggle the state since this condition is
   534  		// detectable
   535  		n.unbalanced = isLeft
   536  		n.right = nil
   537  		if n.initial {
   538  			n.root = true
   539  			return d
   540  		}
   541  		isLeft = n.isLeft
   542  		n = n.parent
   543  		d++
   544  	}
   545  }
   546  
   547  // EOC (end of chunk) implements the error interface
   548  type EOC struct {
   549  	Hash []byte // read the hash of the chunk off the error
   550  }
   551  
   552  // Error returns the error string
   553  func (e *EOC) Error() string {
   554  	return fmt.Sprintf("hasher limit reached, chunk hash: %x", e.Hash)
   555  }
   556  
   557  // NewEOC creates new end of chunk error with the hash
   558  func NewEOC(hash []byte) *EOC {
   559  	return &EOC{hash}
   560  }