2021-07-29 15:00:07 +00:00
package mpt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
)
var (
// ErrRestoreFailed is returned when replacing HashNode by its "unhashed"
// candidate fails.
ErrRestoreFailed = errors . New ( "failed to restore MPT node" )
errStop = errors . New ( "stop condition is met" )
)
2022-04-20 18:30:09 +00:00
// Billet is a part of an MPT trie with missing hash nodes that need to be restored.
2021-07-29 15:00:07 +00:00
// Billet is based on the following assumptions:
2022-08-08 10:23:21 +00:00
// 1. Refcount can only be incremented (we don't change the MPT structure during restore,
// thus don't need to decrease refcount).
// 2. Each time a part of a Billet is completely restored, it is collapsed into
// HashNode.
// 3. Any pair (node, path) must be restored only once. It's a duty of an MPT pool to manage
// MPT paths in order to provide this assumption.
2021-07-29 15:00:07 +00:00
type Billet struct {
2021-09-27 13:35:25 +00:00
TempStoragePrefix storage . KeyPrefix
Store * storage . MemCachedStore
2021-07-29 15:00:07 +00:00
2022-01-28 08:56:33 +00:00
root Node
mode TrieMode
2021-07-29 15:00:07 +00:00
}
2022-04-20 18:30:09 +00:00
// NewBillet returns a new billet for MPT trie restoring. It accepts a MemCachedStore
2021-07-29 15:00:07 +00:00
// to decouple storage errors from logic errors so that all storage errors are
2022-09-02 14:20:39 +00:00
// processed during `store.Persist()` at the caller. Another benefit is
2021-07-29 15:00:07 +00:00
// that every `Put` can be considered an atomic operation.
2022-01-28 08:56:33 +00:00
func NewBillet ( rootHash util . Uint256 , mode TrieMode , prefix storage . KeyPrefix , store * storage . MemCachedStore ) * Billet {
2021-07-29 15:00:07 +00:00
return & Billet {
2021-09-27 13:35:25 +00:00
TempStoragePrefix : prefix ,
Store : store ,
root : NewHashNode ( rootHash ) ,
2022-01-28 08:56:33 +00:00
mode : mode ,
2021-07-29 15:00:07 +00:00
}
}
// RestoreHashNode replaces HashNode located at the provided path by the specified Node
2022-04-20 18:30:09 +00:00
// and stores it. It also maintains the MPT as small as possible by collapsing those parts
// of the MPT that have been completely restored.
2021-07-29 15:00:07 +00:00
func ( b * Billet ) RestoreHashNode ( path [ ] byte , node Node ) error {
if _ , ok := node . ( * HashNode ) ; ok {
return fmt . Errorf ( "%w: unable to restore node into HashNode" , ErrRestoreFailed )
}
if _ , ok := node . ( EmptyNode ) ; ok {
return fmt . Errorf ( "%w: unable to restore node into EmptyNode" , ErrRestoreFailed )
}
r , err := b . putIntoNode ( b . root , path , node )
if err != nil {
return err
}
b . root = r
2021-08-23 09:02:17 +00:00
// If it's a leaf, then put into temporary contract storage.
2021-07-29 15:00:07 +00:00
if leaf , ok := node . ( * LeafNode ) ; ok {
2021-10-20 15:20:31 +00:00
if b . TempStoragePrefix == 0 {
panic ( "invalid storage prefix" )
}
2021-09-27 13:35:25 +00:00
k := append ( [ ] byte { byte ( b . TempStoragePrefix ) } , fromNibbles ( path ) ... )
2022-02-16 14:48:15 +00:00
b . Store . Put ( k , leaf . value )
2021-07-29 15:00:07 +00:00
}
return nil
}
2022-04-20 18:30:09 +00:00
// putIntoNode puts val with the provided path inside curr and returns an updated node.
2021-07-29 15:00:07 +00:00
// Reference counters are updated for both curr and returned value.
func ( b * Billet ) putIntoNode ( curr Node , path [ ] byte , val Node ) ( Node , error ) {
switch n := curr . ( type ) {
case * LeafNode :
return b . putIntoLeaf ( n , path , val )
case * BranchNode :
return b . putIntoBranch ( n , path , val )
case * ExtensionNode :
return b . putIntoExtension ( n , path , val )
case * HashNode :
return b . putIntoHash ( n , path , val )
case EmptyNode :
return nil , fmt . Errorf ( "%w: can't modify EmptyNode during restore" , ErrRestoreFailed )
default :
panic ( "invalid MPT node type" )
}
}
func ( b * Billet ) putIntoLeaf ( curr * LeafNode , path [ ] byte , val Node ) ( Node , error ) {
if len ( path ) != 0 {
return nil , fmt . Errorf ( "%w: can't modify LeafNode during restore" , ErrRestoreFailed )
}
if curr . Hash ( ) != val . Hash ( ) {
return nil , fmt . Errorf ( "%w: bad Leaf node hash: expected %s, got %s" , ErrRestoreFailed , curr . Hash ( ) . StringBE ( ) , val . Hash ( ) . StringBE ( ) )
}
2021-08-11 13:09:50 +00:00
// Once Leaf node is restored, it will be collapsed into HashNode forever, so
2022-04-20 18:30:09 +00:00
// there shouldn't be such situation when we try to restore a Leaf node.
2021-08-11 13:09:50 +00:00
panic ( "bug: can't restore LeafNode" )
2021-07-29 15:00:07 +00:00
}
func ( b * Billet ) putIntoBranch ( curr * BranchNode , path [ ] byte , val Node ) ( Node , error ) {
if len ( path ) == 0 && curr . Hash ( ) . Equals ( val . Hash ( ) ) {
2021-08-11 13:09:50 +00:00
// This node has already been restored, so it's an MPT pool duty to avoid
// duplicating restore requests.
panic ( "bug: can't perform restoring of BranchNode twice" )
2021-07-29 15:00:07 +00:00
}
i , path := splitPath ( path )
r , err := b . putIntoNode ( curr . Children [ i ] , path , val )
if err != nil {
return nil , err
}
curr . Children [ i ] = r
2021-08-11 13:09:50 +00:00
return b . tryCollapseBranch ( curr ) , nil
2021-07-29 15:00:07 +00:00
}
func ( b * Billet ) putIntoExtension ( curr * ExtensionNode , path [ ] byte , val Node ) ( Node , error ) {
if len ( path ) == 0 {
if curr . Hash ( ) != val . Hash ( ) {
return nil , fmt . Errorf ( "%w: bad Extension node hash: expected %s, got %s" , ErrRestoreFailed , curr . Hash ( ) . StringBE ( ) , val . Hash ( ) . StringBE ( ) )
}
2021-08-11 13:09:50 +00:00
// This node has already been restored, so it's an MPT pool duty to avoid
// duplicating restore requests.
panic ( "bug: can't perform restoring of ExtensionNode twice" )
2021-07-29 15:00:07 +00:00
}
if ! bytes . HasPrefix ( path , curr . key ) {
return nil , fmt . Errorf ( "%w: can't modify ExtensionNode during restore" , ErrRestoreFailed )
}
r , err := b . putIntoNode ( curr . next , path [ len ( curr . key ) : ] , val )
if err != nil {
return nil , err
}
curr . next = r
2021-08-11 13:09:50 +00:00
return b . tryCollapseExtension ( curr ) , nil
2021-07-29 15:00:07 +00:00
}
func ( b * Billet ) putIntoHash ( curr * HashNode , path [ ] byte , val Node ) ( Node , error ) {
2022-04-20 18:30:09 +00:00
// Once a part of the MPT Billet is completely restored, it will be collapsed forever, so
2021-07-29 15:00:07 +00:00
// it's an MPT pool duty to avoid duplicating restore requests.
if len ( path ) != 0 {
return nil , fmt . Errorf ( "%w: node has already been collapsed" , ErrRestoreFailed )
}
// `curr` hash node can be either of
2022-04-20 18:30:09 +00:00
// 1) saved in the storage (i.g. if we've already restored a node with the same hash from the
// other part of the MPT), so just add it to the local in-memory MPT.
2021-07-29 15:00:07 +00:00
// 2) missing from the storage. It's OK because we're syncing MPT state, and the purpose
// is to store missing hash nodes.
// both cases are OK, but we still need to validate `val` against `curr`.
if val . Hash ( ) != curr . Hash ( ) {
return nil , fmt . Errorf ( "%w: can't restore HashNode: expected and actual hashes mismatch (%s vs %s)" , ErrRestoreFailed , curr . Hash ( ) . StringBE ( ) , val . Hash ( ) . StringBE ( ) )
}
2021-08-11 13:09:50 +00:00
if curr . Collapsed {
// This node has already been restored and collapsed, so it's an MPT pool duty to avoid
// duplicating restore requests.
panic ( "bug: can't perform restoring of collapsed node" )
}
2021-07-29 15:00:07 +00:00
// We also need to increment refcount in both cases. That's the only place where refcount
// is changed during restore process. Also flush right now, because sync process can be
// interrupted at any time.
b . incrementRefAndStore ( val . Hash ( ) , val . Bytes ( ) )
2021-08-11 13:09:50 +00:00
if val . Type ( ) == LeafT {
return b . tryCollapseLeaf ( val . ( * LeafNode ) ) , nil
}
2021-07-29 15:00:07 +00:00
return val , nil
}
func ( b * Billet ) incrementRefAndStore ( h util . Uint256 , bs [ ] byte ) {
2022-01-27 11:25:11 +00:00
key := makeStorageKey ( h )
2022-01-28 08:56:33 +00:00
if b . mode . RC ( ) {
2021-07-29 15:00:07 +00:00
var (
err error
data [ ] byte
cnt int32
)
// An item may already be in store.
data , err = b . Store . Get ( key )
if err == nil {
cnt = int32 ( binary . LittleEndian . Uint32 ( data [ len ( data ) - 4 : ] ) )
}
cnt ++
if len ( data ) == 0 {
2022-01-28 12:05:13 +00:00
data = append ( bs , 1 , 0 , 0 , 0 , 0 )
2021-07-29 15:00:07 +00:00
}
binary . LittleEndian . PutUint32 ( data [ len ( data ) - 4 : ] , uint32 ( cnt ) )
2022-02-16 14:48:15 +00:00
b . Store . Put ( key , data )
2021-07-29 15:00:07 +00:00
} else {
2022-02-16 14:48:15 +00:00
b . Store . Put ( key , bs )
2021-07-29 15:00:07 +00:00
}
}
// Traverse traverses MPT nodes (pre-order) starting from the billet root down
// to its children calling `process` for each serialised node until true is
// returned from `process` function. It also replaces all HashNodes to their
// "unhashed" counterparts until the stop condition is satisfied.
2021-10-07 13:56:27 +00:00
func ( b * Billet ) Traverse ( process func ( pathToNode [ ] byte , node Node , nodeBytes [ ] byte ) bool , ignoreStorageErr bool ) error {
2022-04-07 15:11:05 +00:00
r , err := b . traverse ( b . root , [ ] byte { } , [ ] byte { } , process , ignoreStorageErr , false )
2021-07-29 15:00:07 +00:00
if err != nil && ! errors . Is ( err , errStop ) {
return err
}
b . root = r
return nil
}
2022-04-07 15:11:05 +00:00
func ( b * Billet ) traverse ( curr Node , path , from [ ] byte , process func ( pathToNode [ ] byte , node Node , nodeBytes [ ] byte ) bool , ignoreStorageErr bool , backwards bool ) ( Node , error ) {
2021-07-29 15:00:07 +00:00
if _ , ok := curr . ( EmptyNode ) ; ok {
// We're not interested in EmptyNodes, and they do not affect the
// traversal process, thus remain them untouched.
return curr , nil
}
if hn , ok := curr . ( * HashNode ) ; ok {
2021-08-13 09:46:23 +00:00
r , err := b . GetFromStore ( hn . Hash ( ) )
2021-07-29 15:00:07 +00:00
if err != nil {
if ignoreStorageErr && errors . Is ( err , storage . ErrKeyNotFound ) {
return hn , nil
}
return nil , err
}
2022-04-07 15:11:05 +00:00
return b . traverse ( r , path , from , process , ignoreStorageErr , backwards )
2021-07-29 15:00:07 +00:00
}
2021-10-13 07:22:57 +00:00
if len ( from ) == 0 {
2021-10-07 13:56:27 +00:00
bytes := slice . Copy ( curr . Bytes ( ) )
if process ( fromNibbles ( path ) , curr , bytes ) {
return curr , errStop
}
2021-07-29 15:00:07 +00:00
}
switch n := curr . ( type ) {
case * LeafNode :
2021-08-11 13:09:50 +00:00
return b . tryCollapseLeaf ( n ) , nil
2021-07-29 15:00:07 +00:00
case * BranchNode :
2021-10-13 07:22:57 +00:00
var (
startIndex byte
endIndex byte = childrenCount
2022-04-07 15:11:05 +00:00
cmp = func ( i int ) bool {
return i < int ( endIndex )
}
step = 1
2021-10-13 07:22:57 +00:00
)
2022-04-07 15:11:05 +00:00
if backwards {
startIndex , endIndex = lastChild , startIndex
cmp = func ( i int ) bool {
return i >= int ( endIndex )
}
step = - 1
}
2021-10-13 07:22:57 +00:00
if len ( from ) != 0 {
endIndex = lastChild
2022-04-07 15:11:05 +00:00
if backwards {
endIndex = 0
}
2021-10-13 07:22:57 +00:00
startIndex , from = splitPath ( from )
2021-10-07 13:56:27 +00:00
}
2022-04-07 15:11:05 +00:00
for i := int ( startIndex ) ; cmp ( i ) ; i += step {
2021-10-07 13:56:27 +00:00
var newPath [ ] byte
if i == lastChild {
newPath = path
} else {
2022-04-07 15:11:05 +00:00
newPath = append ( path , byte ( i ) )
2021-10-13 07:22:57 +00:00
}
2022-04-07 15:11:05 +00:00
if byte ( i ) != startIndex {
2021-10-13 07:22:57 +00:00
from = [ ] byte { }
2021-10-07 13:56:27 +00:00
}
2022-04-07 15:11:05 +00:00
r , err := b . traverse ( n . Children [ i ] , newPath , from , process , ignoreStorageErr , backwards )
2021-07-29 15:00:07 +00:00
if err != nil {
if ! errors . Is ( err , errStop ) {
return nil , err
}
n . Children [ i ] = r
2021-10-13 10:48:18 +00:00
return b . tryCollapseBranch ( n ) , err
2021-07-29 15:00:07 +00:00
}
n . Children [ i ] = r
}
2021-08-11 13:09:50 +00:00
return b . tryCollapseBranch ( n ) , nil
2021-07-29 15:00:07 +00:00
case * ExtensionNode :
2021-10-13 07:22:57 +00:00
if len ( from ) != 0 && bytes . HasPrefix ( from , n . key ) {
from = from [ len ( n . key ) : ]
} else if len ( from ) == 0 || bytes . Compare ( n . key , from ) > 0 {
from = [ ] byte { }
2021-10-07 13:56:27 +00:00
} else {
return b . tryCollapseExtension ( n ) , nil
}
2022-04-07 15:11:05 +00:00
r , err := b . traverse ( n . next , append ( path , n . key ... ) , from , process , ignoreStorageErr , backwards )
2021-07-29 15:00:07 +00:00
if err != nil && ! errors . Is ( err , errStop ) {
return nil , err
}
n . next = r
2021-10-13 10:48:18 +00:00
return b . tryCollapseExtension ( n ) , err
2021-07-29 15:00:07 +00:00
default :
return nil , ErrNotFound
}
}
2021-08-11 13:09:50 +00:00
func ( b * Billet ) tryCollapseLeaf ( curr * LeafNode ) Node {
// Leaf can always be collapsed.
res := NewHashNode ( curr . Hash ( ) )
res . Collapsed = true
return res
}
func ( b * Billet ) tryCollapseExtension ( curr * ExtensionNode ) Node {
if ! ( curr . next . Type ( ) == HashT && curr . next . ( * HashNode ) . Collapsed ) {
return curr
}
res := NewHashNode ( curr . Hash ( ) )
res . Collapsed = true
return res
}
func ( b * Billet ) tryCollapseBranch ( curr * BranchNode ) Node {
canCollapse := true
for i := 0 ; i < childrenCount ; i ++ {
if curr . Children [ i ] . Type ( ) == EmptyT {
continue
}
if curr . Children [ i ] . Type ( ) == HashT && curr . Children [ i ] . ( * HashNode ) . Collapsed {
continue
}
canCollapse = false
break
}
if ! canCollapse {
return curr
}
res := NewHashNode ( curr . Hash ( ) )
res . Collapsed = true
return res
}
2021-08-13 09:46:23 +00:00
// GetFromStore returns MPT node from the storage.
func ( b * Billet ) GetFromStore ( h util . Uint256 ) ( Node , error ) {
2022-01-27 11:25:11 +00:00
data , err := b . Store . Get ( makeStorageKey ( h ) )
2021-07-29 15:00:07 +00:00
if err != nil {
return nil , err
}
var n NodeObject
r := io . NewBinReaderFromBuf ( data )
n . DecodeBinary ( r )
if r . Err != nil {
return nil , r . Err
}
2022-01-28 08:56:33 +00:00
if b . mode . RC ( ) {
2022-01-28 12:05:13 +00:00
data = data [ : len ( data ) - 5 ]
2021-07-29 15:00:07 +00:00
}
n . Node . ( flushedNode ) . setCache ( data , h )
return n . Node , nil
}