github.com/bartle-stripe/trillian@v1.2.1/storage/types.go (about) 1 // Copyright 2016 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package storage 16 17 import ( 18 "bytes" 19 "encoding/binary" 20 "fmt" 21 "math/big" 22 "math/bits" 23 24 "github.com/golang/glog" 25 "github.com/google/trillian/storage/storagepb" 26 ) 27 28 // Node represents a single node in a Merkle tree. 29 type Node struct { 30 NodeID NodeID 31 Hash []byte 32 NodeRevision int64 33 } 34 35 // NodeID uniquely identifies a Node within a versioned MerkleTree. 36 type NodeID struct { 37 // path is effectively a BigEndian bit set, with path[0] being the MSB 38 // (identifying the root child), and successive bits identifying the lower 39 // level children down to the leaf. 40 Path []byte 41 // PrefixLenBits is the number of MSB in Path which are considered part of 42 // this NodeID. 43 // 44 // e.g. if Path contains two bytes, and PrefixLenBits is 9, then the 8 bits 45 // in Path[0] are included, along with the lowest bit of Path[1] 46 PrefixLenBits int 47 } 48 49 // PathLenBits returns 8 * len(path). 50 func (n NodeID) PathLenBits() int { 51 return len(n.Path) * 8 52 } 53 54 // bytesForBits returns the number of bytes required to store numBits bits. 55 func bytesForBits(numBits int) int { 56 return (numBits + 7) >> 3 57 } 58 59 // NewNodeIDFromHash creates a new NodeID for the given Hash. 60 func NewNodeIDFromHash(h []byte) NodeID { 61 return NodeID{ 62 Path: h, 63 PrefixLenBits: len(h) * 8, 64 } 65 } 66 67 // NewEmptyNodeID creates a new zero-length NodeID with sufficient underlying 68 // capacity to store a maximum of maxLenBits. 69 func NewEmptyNodeID(maxLenBits int) NodeID { 70 if got, want := maxLenBits%8, 0; got != want { 71 panic(fmt.Sprintf("storeage: NewEmptyNodeID() maxLenBits mod 8: %v, want %v", got, want)) 72 } 73 return NodeID{ 74 Path: make([]byte, maxLenBits/8), 75 PrefixLenBits: 0, 76 } 77 } 78 79 // NewNodeIDFromPrefix returns a nodeID for a particular node within a subtree. 80 // Prefix is the prefix of the subtree. 81 // depth is the depth of index from the root of the subtree. 82 // index is the horizontal location of the subtree leaf. 83 // subDepth is the total number of levels in the subtree. 84 // totalDepth is the number of levels in the whole tree. 85 func NewNodeIDFromPrefix(prefix []byte, depth int, index int64, subDepth, totalDepth int) NodeID { 86 if got, want := totalDepth%8, 0; got != want || got < want { 87 panic(fmt.Sprintf("storage NewNodeFromPrefix(): totalDepth mod 8: %v, want %v", got, want)) 88 } 89 if got, want := subDepth%8, 0; got != want || got < want { 90 panic(fmt.Sprintf("storage NewNodeFromPrefix(): subDepth mod 8: %v, want %v", got, want)) 91 } 92 if got, want := depth, 0; got < want { 93 panic(fmt.Sprintf("storage NewNodeFromPrefix(): depth: %v, want >= %v", got, want)) 94 } 95 96 // Put prefix in the MSB bits of path. 97 path := make([]byte, totalDepth/8) 98 copy(path, prefix) 99 100 // Convert index into absolute coordinates for subtree. 101 height := subDepth - depth 102 subIndex := index << uint(height) // index is the horizontal index at the given height. 103 104 // Copy subDepth/8 bytes of subIndex into path. 105 subPath := new(bytes.Buffer) 106 binary.Write(subPath, binary.BigEndian, uint64(subIndex)) 107 unusedHighBytes := 64/8 - subDepth/8 108 copy(path[len(prefix):], subPath.Bytes()[unusedHighBytes:]) 109 110 return NodeID{ 111 Path: path, 112 PrefixLenBits: len(prefix)*8 + depth, 113 } 114 } 115 116 // NewNodeIDFromBigInt returns a NodeID of a big.Int with no prefix. 117 // index contains the path's least significant bits. 118 // depth indicates the number of bits from the most significant bit to treat as part of the path. 119 func NewNodeIDFromBigInt(depth int, index *big.Int, totalDepth int) NodeID { 120 if got, want := totalDepth%8, 0; got != want || got < want { 121 panic(fmt.Sprintf("storage NewNodeFromBitInt(): totalDepth mod 8: %v, want %v", got, want)) 122 } 123 124 // Put index in the LSB bits of path. 125 path := make([]byte, totalDepth/8) 126 unusedHighBytes := len(path) - len(index.Bytes()) 127 copy(path[unusedHighBytes:], index.Bytes()) 128 129 // TODO(gdbelvin): consider masking off insignificant bits past depth. 130 glog.V(5).Infof("NewNodeIDFromBigInt(%v, %x, %v): %v, %x", 131 depth, index.Bytes(), totalDepth, depth, path) 132 133 return NodeID{ 134 Path: path, 135 PrefixLenBits: depth, 136 } 137 } 138 139 // BigInt returns the big.Int for this node. 140 func (n NodeID) BigInt() *big.Int { 141 return new(big.Int).SetBytes(n.Path) 142 } 143 144 // NewNodeIDWithPrefix creates a new NodeID of nodeIDLen bits with the prefixLen MSBs set to prefix. 145 // NewNodeIDWithPrefix places the lower prefixLenBits of prefix in the most significant bits of path. 146 // Path will have enough bytes to hold maxLenBits 147 // 148 func NewNodeIDWithPrefix(prefix uint64, prefixLenBits, nodeIDLenBits, maxLenBits int) NodeID { 149 if got, want := nodeIDLenBits%8, 0; got != want { 150 panic(fmt.Sprintf("nodeIDLenBits mod 8: %v, want %v", got, want)) 151 } 152 maxLenBytes := bytesForBits(maxLenBits) 153 p := NodeID{ 154 Path: make([]byte, maxLenBytes), 155 PrefixLenBits: nodeIDLenBits, 156 } 157 158 bit := maxLenBits - prefixLenBits 159 for i := 0; i < prefixLenBits; i++ { 160 if prefix&1 != 0 { 161 p.SetBit(bit, 1) 162 } 163 bit++ 164 prefix >>= 1 165 } 166 return p 167 } 168 169 // NewNodeIDForTreeCoords creates a new NodeID for a Tree node with a specified depth and 170 // index. 171 // This method is used exclusively by the Log, and, since the Log model grows upwards from the 172 // leaves, we modify the provided coords accordingly. 173 // 174 // depth is the Merkle tree level: 0 = leaves, and increases upwards towards the root. 175 // 176 // index is the horizontal index into the tree at level depth, so the returned 177 // NodeID will be zero padded on the right by depth places. 178 func NewNodeIDForTreeCoords(depth int64, index int64, maxPathBits int) (NodeID, error) { 179 bl := bits.Len64(uint64(index)) 180 if index < 0 || depth < 0 || 181 bl > int(maxPathBits-int(depth)) || 182 maxPathBits%8 != 0 { 183 return NodeID{}, fmt.Errorf("depth/index combination out of range: depth=%d index=%d maxPathBits=%v", depth, index, maxPathBits) 184 } 185 // This node is effectively a prefix of the subtree underneath (for non-leaf 186 // depths), so we shift the index accordingly. 187 uidx := uint64(index) << uint(depth) 188 r := NewEmptyNodeID(maxPathBits) 189 for i := len(r.Path) - 1; uidx > 0 && i >= 0; i-- { 190 r.Path[i] = byte(uidx & 0xff) 191 uidx >>= 8 192 } 193 // In the storage model nodes closer to the leaves have longer nodeIDs, so 194 // we "reverse" depth here: 195 r.PrefixLenBits = int(maxPathBits - int(depth)) 196 return r, nil 197 } 198 199 // SetBit sets the ith bit to true if b is non-zero, and false otherwise. 200 func (n *NodeID) SetBit(i int, b uint) { 201 // TODO(al): investigate whether having lookup tables for these might be 202 // faster. 203 bIndex := (n.PathLenBits() - i - 1) / 8 204 if b == 0 { 205 n.Path[bIndex] &= ^(1 << uint(i%8)) 206 } else { 207 n.Path[bIndex] |= (1 << uint(i%8)) 208 } 209 } 210 211 // Bit returns 1 if the ith bit from the right is true, and false otherwise. 212 func (n *NodeID) Bit(i int) uint { 213 if got, want := i, n.PathLenBits()-1; got > want { 214 panic(fmt.Sprintf("storage: Bit(%v) > (PathLenBits() -1): %v", got, want)) 215 } 216 bIndex := (n.PathLenBits() - i - 1) / 8 217 return uint((n.Path[bIndex] >> uint(i%8)) & 0x01) 218 } 219 220 // String returns a string representation of the binary value of the NodeID. 221 // The left-most bit is the MSB (i.e. nearer the root of the tree). 222 func (n *NodeID) String() string { 223 var r bytes.Buffer 224 limit := n.PathLenBits() - n.PrefixLenBits 225 for i := n.PathLenBits() - 1; i >= limit; i-- { 226 r.WriteRune(rune('0' + n.Bit(i))) 227 } 228 return r.String() 229 } 230 231 // CoordString returns a string representation assuming that the NodeID represents a 232 // tree coordinate. Using this on a NodeID for a sparse Merkle tree will give incorrect 233 // results. Intended for debugging purposes, the format could change. 234 func (n *NodeID) CoordString() string { 235 d := uint64(n.PathLenBits() - n.PrefixLenBits) 236 i := uint64(0) 237 for _, p := range n.Path { 238 i = (i << uint64(8)) + uint64(p) 239 } 240 241 return fmt.Sprintf("[d:%d, i:%d]", d, i>>d) 242 } 243 244 // Copy returns a duplicate of NodeID 245 func (n *NodeID) Copy() *NodeID { 246 p := make([]byte, len(n.Path)) 247 copy(p, n.Path) 248 return &NodeID{ 249 Path: p, 250 PrefixLenBits: n.PrefixLenBits, 251 } 252 } 253 254 // FlipRightBit flips the ith bit from LSB 255 func (n *NodeID) FlipRightBit(i int) *NodeID { 256 n.SetBit(i, n.Bit(i)^1) 257 return n 258 } 259 260 // leftmask contains bitmasks indexed such that the left x bits are set. It is 261 // indexed by byte position from 0-7 0 is special cased to 0xFF since 8 mod 8 262 // is 0. leftmask is only used to mask the last byte. 263 var leftmask = [8]byte{0xFF, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE} 264 265 // MaskLeft returns NodeID with only the left n bits set 266 func (n *NodeID) MaskLeft(depth int) *NodeID { 267 r := make([]byte, len(n.Path)) 268 if depth > 0 { 269 // Copy the first depthBytes. 270 depthBytes := bytesForBits(depth) 271 copy(r, n.Path[:depthBytes]) 272 // Mask off unwanted bits in the last byte. 273 r[depthBytes-1] = r[depthBytes-1] & leftmask[depth%8] 274 } 275 if depth < n.PrefixLenBits { 276 n.PrefixLenBits = depth 277 } 278 n.Path = r 279 return n 280 } 281 282 // Neighbor returns the same node with the bit at PrefixLenBits flipped. 283 func (n *NodeID) Neighbor() *NodeID { 284 height := n.PathLenBits() - n.PrefixLenBits 285 n.FlipRightBit(height) 286 return n 287 } 288 289 // Siblings returns the siblings of the given node. 290 func (n *NodeID) Siblings() []NodeID { 291 sibs := make([]NodeID, n.PrefixLenBits) 292 for height := range sibs { 293 depth := n.PrefixLenBits - height 294 sibs[height] = *(n.Copy().MaskLeft(depth).Neighbor()) 295 } 296 return sibs 297 } 298 299 // NewNodeIDFromPrefixSuffix undoes Split() and returns the NodeID. 300 func NewNodeIDFromPrefixSuffix(prefix []byte, suffix Suffix, maxPathBits int) NodeID { 301 path := make([]byte, maxPathBits/8) 302 copy(path, prefix) 303 copy(path[len(prefix):], suffix.Path) 304 305 return NodeID{ 306 Path: path, 307 PrefixLenBits: len(prefix)*8 + int(suffix.Bits), 308 } 309 } 310 311 // Split splits a NodeID into a prefix and a suffix at prefixSplit 312 func (n *NodeID) Split(prefixBytes, suffixBits int) ([]byte, Suffix) { 313 if n.PrefixLenBits == 0 { 314 return []byte{}, Suffix{Bits: 0, Path: []byte{0}} 315 } 316 a := make([]byte, len(n.Path)) 317 copy(a, n.Path) 318 319 bits := n.PrefixLenBits - prefixBytes*8 320 if bits > suffixBits { 321 panic(fmt.Sprintf("storage Split: %x(n.PrefixLenBits: %v - prefixBytes: %v *8) > %v", n.Path, n.PrefixLenBits, prefixBytes, suffixBits)) 322 } 323 if bits == 0 { 324 panic(fmt.Sprintf("storage Split: %x(n.PrefixLenBits: %v - prefixBytes: %v *8) == 0", n.Path, n.PrefixLenBits, prefixBytes)) 325 } 326 suffixBytes := bytesForBits(bits) 327 sfx := Suffix{ 328 Bits: byte(bits), 329 Path: a[prefixBytes : prefixBytes+suffixBytes], 330 } 331 maskIndex := (bits - 1) / 8 332 maskLowBits := (sfx.Bits-1)%8 + 1 333 sfx.Path[maskIndex] &= ((0x01 << maskLowBits) - 1) << uint(8-maskLowBits) 334 335 return a[:prefixBytes], sfx 336 } 337 338 // Equivalent return true iff the other represents the same path prefix as this NodeID. 339 func (n *NodeID) Equivalent(other NodeID) bool { 340 return n.String() == other.String() 341 } 342 343 // PopulateSubtreeFunc is a function which knows how to re-populate a subtree 344 // from just its leaf nodes. 345 type PopulateSubtreeFunc func(*storagepb.SubtreeProto) error 346 347 // PrepareSubtreeWriteFunc is a function that carries out any required tree type specific 348 // manipulation of a subtree before it's written to storage 349 type PrepareSubtreeWriteFunc func(*storagepb.SubtreeProto) error