github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/bmt/bmt.go (about)

     1  // Copyright 2017 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum 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 righmost 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 uptil it has no more than n resources
   153  func (self *TreePool) Drain(n int) {
   154  	self.lock.Lock()
   155  	defer self.lock.Unlock()
   156  	for len(self.c) > n {
   157  		<-self.c
   158  		self.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 (self *TreePool) Reserve() *Tree {
   165  	self.lock.Lock()
   166  	defer self.lock.Unlock()
   167  	var t *Tree
   168  	if self.count == self.Capacity {
   169  		return <-self.c
   170  	}
   171  	select {
   172  	case t = <-self.c:
   173  	default:
   174  		t = NewTree(self.hasher, self.SegmentSize, self.SegmentCount)
   175  		self.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 (self *TreePool) Release(t *Tree) {
   184  	self.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 (self *Tree) Draw(hash []byte, d int) string {
   197  	var left, right []string
   198  	var anc []*Node
   199  	for i, n := range self.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 = self.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 (self *Hasher) Size() int {
   281  	return self.size
   282  }
   283  
   284  // BlockSize returns the block size
   285  func (self *Hasher) BlockSize() int {
   286  	return self.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 (self *Hasher) Sum(b []byte) (r []byte) {
   293  	t := self.bmt
   294  	i := self.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(self.segment) > self.size && i > 0 && n.parent != nil {
   300  		n = n.parent
   301  	} else {
   302  		i *= 2
   303  	}
   304  	d := self.finalise(n, i)
   305  	self.writeSegment(j, self.segment, d)
   306  	c := <-self.result
   307  	self.releaseTree()
   308  
   309  	// sha3(length + BMT(pure_chunk))
   310  	if self.blockLength == nil {
   311  		return c
   312  	}
   313  	res := self.pool.hasher()
   314  	res.Reset()
   315  	res.Write(self.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 (self *Hasher) Hash() []byte {
   325  	return <-self.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 (self *Hasher) Write(b []byte) (int, error) {
   334  	l := len(b)
   335  	if l <= 0 {
   336  		return 0, nil
   337  	}
   338  	s := self.segment
   339  	i := self.cur
   340  	count := (self.count + 1) / 2
   341  	need := self.count*self.size - self.cur*2*self.size
   342  	size := self.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  		self.writeSegment(i, s, self.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  	self.segment = s
   369  	self.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 (self *Hasher) ReadFrom(r io.Reader) (m int64, err error) {
   380  	bufsize := self.size*self.count - self.size*self.cur - len(self.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 := self.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 = self.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 (self *Hasher) Reset() {
   407  	self.getTree()
   408  	self.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 legth of the data subsumed under the hash
   416  func (self *Hasher) ResetWithLength(l []byte) {
   417  	self.Reset()
   418  	self.blockLength = l
   419  
   420  }
   421  
   422  // Release gives back the Tree to the pool whereby it unlocks
   423  // it resets tree, segment and index
   424  func (self *Hasher) releaseTree() {
   425  	if self.bmt != nil {
   426  		n := self.bmt.leaves[self.cur]
   427  		for ; n != nil; n = n.parent {
   428  			n.unbalanced = false
   429  			if n.parent != nil {
   430  				n.root = false
   431  			}
   432  		}
   433  		self.pool.Release(self.bmt)
   434  		self.bmt = nil
   435  
   436  	}
   437  	self.cur = 0
   438  	self.segment = nil
   439  }
   440  
   441  func (self *Hasher) writeSegment(i int, s []byte, d int) {
   442  	h := self.pool.hasher()
   443  	n := self.bmt.leaves[i]
   444  
   445  	if len(s) > self.size && n.parent != nil {
   446  		go func() {
   447  			h.Reset()
   448  			h.Write(s)
   449  			s = h.Sum(nil)
   450  
   451  			if n.root {
   452  				self.result <- s
   453  				return
   454  			}
   455  			self.run(n.parent, h, d, n.index, s)
   456  		}()
   457  		return
   458  	}
   459  	go self.run(n, h, d, i*2, s)
   460  }
   461  
   462  func (self *Hasher) run(n *Node, h hash.Hash, d int, i int, s []byte) {
   463  	isLeft := i%2 == 0
   464  	for {
   465  		if isLeft {
   466  			n.left = s
   467  		} else {
   468  			n.right = s
   469  		}
   470  		if !n.unbalanced && n.toggle() {
   471  			return
   472  		}
   473  		if !n.unbalanced || !isLeft || i == 0 && d == 0 {
   474  			h.Reset()
   475  			h.Write(n.left)
   476  			h.Write(n.right)
   477  			s = h.Sum(nil)
   478  
   479  		} else {
   480  			s = append(n.left, n.right...)
   481  		}
   482  
   483  		self.hash = s
   484  		if n.root {
   485  			self.result <- s
   486  			return
   487  		}
   488  
   489  		isLeft = n.isLeft
   490  		n = n.parent
   491  		i++
   492  	}
   493  }
   494  
   495  // getTree obtains a BMT resource by reserving one from the pool
   496  func (self *Hasher) getTree() *Tree {
   497  	if self.bmt != nil {
   498  		return self.bmt
   499  	}
   500  	t := self.pool.Reserve()
   501  	self.bmt = t
   502  	return t
   503  }
   504  
   505  // atomic bool toggle implementing a concurrent reusable 2-state object
   506  // atomic addint with %2 implements atomic bool toggle
   507  // it returns true if the toggler just put it in the active/waiting state
   508  func (self *Node) toggle() bool {
   509  	return atomic.AddInt32(&self.state, 1)%2 == 1
   510  }
   511  
   512  func hashstr(b []byte) string {
   513  	end := len(b)
   514  	if end > 4 {
   515  		end = 4
   516  	}
   517  	return fmt.Sprintf("%x", b[:end])
   518  }
   519  
   520  func depth(n int) (d int) {
   521  	for l := (n - 1) / 2; l > 0; l /= 2 {
   522  		d++
   523  	}
   524  	return d
   525  }
   526  
   527  // finalise is following the zigzags on the tree belonging
   528  // to the final datasegment
   529  func (self *Hasher) finalise(n *Node, i int) (d int) {
   530  	isLeft := i%2 == 0
   531  	for {
   532  		// when the final segment's path is going via left segments
   533  		// the incoming data is pushed to the parent upon pulling the left
   534  		// we do not need toogle the state since this condition is
   535  		// detectable
   536  		n.unbalanced = isLeft
   537  		n.right = nil
   538  		if n.initial {
   539  			n.root = true
   540  			return d
   541  		}
   542  		isLeft = n.isLeft
   543  		n = n.parent
   544  		d++
   545  	}
   546  }
   547  
   548  // EOC (end of chunk) implements the error interface
   549  type EOC struct {
   550  	Hash []byte // read the hash of the chunk off the error
   551  }
   552  
   553  // Error returns the error string
   554  func (self *EOC) Error() string {
   555  	return fmt.Sprintf("hasher limit reached, chunk hash: %x", self.Hash)
   556  }
   557  
   558  // NewEOC creates new end of chunk error with the hash
   559  func NewEOC(hash []byte) *EOC {
   560  	return &EOC{hash}
   561  }