|
| 1 | +package cascadekit |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + |
| 8 | + actiontypes "github.com/LumeraProtocol/lumera/x/action/v1/types" |
| 9 | + "github.com/LumeraProtocol/lumera/x/action/v1/merkle" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + // DefaultChunkSize is the default chunk size for LEP-5 commitment (256 KiB). |
| 14 | + DefaultChunkSize = 262144 |
| 15 | + // MinChunkSize is the minimum allowed chunk size. |
| 16 | + MinChunkSize = 1 |
| 17 | + // MaxChunkSize is the maximum allowed chunk size. |
| 18 | + MaxChunkSize = 262144 |
| 19 | + // MinTotalSize is the minimum file size for LEP-5 commitment. |
| 20 | + MinTotalSize = 4 |
| 21 | + // CommitmentType is the commitment type constant for LEP-5. |
| 22 | + CommitmentType = "lep5/chunk-merkle/v1" |
| 23 | +) |
| 24 | + |
| 25 | +// SelectChunkSize returns the optimal chunk size for a given file size and |
| 26 | +// minimum chunk count. It starts at DefaultChunkSize and halves until the |
| 27 | +// file produces at least minChunks chunks. |
| 28 | +func SelectChunkSize(fileSize int64, minChunks uint32) uint32 { |
| 29 | + s := uint32(DefaultChunkSize) |
| 30 | + for numChunks(fileSize, s) < minChunks && s > MinChunkSize { |
| 31 | + s /= 2 |
| 32 | + } |
| 33 | + return s |
| 34 | +} |
| 35 | + |
| 36 | +func numChunks(fileSize int64, chunkSize uint32) uint32 { |
| 37 | + n := uint32(fileSize / int64(chunkSize)) |
| 38 | + if fileSize%int64(chunkSize) != 0 { |
| 39 | + n++ |
| 40 | + } |
| 41 | + return n |
| 42 | +} |
| 43 | + |
| 44 | +// ChunkFile reads a file and returns its chunks using the given chunk size. |
| 45 | +func ChunkFile(path string, chunkSize uint32) ([][]byte, error) { |
| 46 | + f, err := os.Open(path) |
| 47 | + if err != nil { |
| 48 | + return nil, fmt.Errorf("open file: %w", err) |
| 49 | + } |
| 50 | + defer f.Close() |
| 51 | + |
| 52 | + fi, err := f.Stat() |
| 53 | + if err != nil { |
| 54 | + return nil, fmt.Errorf("stat file: %w", err) |
| 55 | + } |
| 56 | + |
| 57 | + totalSize := fi.Size() |
| 58 | + n := numChunks(totalSize, chunkSize) |
| 59 | + chunks := make([][]byte, 0, n) |
| 60 | + |
| 61 | + buf := make([]byte, chunkSize) |
| 62 | + for { |
| 63 | + nr, err := io.ReadFull(f, buf) |
| 64 | + if nr > 0 { |
| 65 | + chunk := make([]byte, nr) |
| 66 | + copy(chunk, buf[:nr]) |
| 67 | + chunks = append(chunks, chunk) |
| 68 | + } |
| 69 | + if err == io.EOF || err == io.ErrUnexpectedEOF { |
| 70 | + break |
| 71 | + } |
| 72 | + if err != nil { |
| 73 | + return nil, fmt.Errorf("read chunk: %w", err) |
| 74 | + } |
| 75 | + } |
| 76 | + return chunks, nil |
| 77 | +} |
| 78 | + |
| 79 | +// BuildCommitmentFromFile constructs an AvailabilityCommitment for a file. |
| 80 | +// It chunks the file, builds a Merkle tree, and generates challenge indices. |
| 81 | +// challengeCount and minChunks are the SVC parameters from the chain. |
| 82 | +func BuildCommitmentFromFile(filePath string, challengeCount, minChunks uint32) (*actiontypes.AvailabilityCommitment, *merkle.Tree, error) { |
| 83 | + fi, err := os.Stat(filePath) |
| 84 | + if err != nil { |
| 85 | + return nil, nil, fmt.Errorf("stat file: %w", err) |
| 86 | + } |
| 87 | + totalSize := fi.Size() |
| 88 | + if totalSize < MinTotalSize { |
| 89 | + return nil, nil, fmt.Errorf("file too small: %d bytes (minimum %d)", totalSize, MinTotalSize) |
| 90 | + } |
| 91 | + |
| 92 | + chunkSize := SelectChunkSize(totalSize, minChunks) |
| 93 | + nc := numChunks(totalSize, chunkSize) |
| 94 | + if nc < minChunks { |
| 95 | + return nil, nil, fmt.Errorf("file produces %d chunks, need at least %d", nc, minChunks) |
| 96 | + } |
| 97 | + |
| 98 | + chunks, err := ChunkFile(filePath, chunkSize) |
| 99 | + if err != nil { |
| 100 | + return nil, nil, err |
| 101 | + } |
| 102 | + |
| 103 | + tree, err := merkle.BuildTree(chunks) |
| 104 | + if err != nil { |
| 105 | + return nil, nil, fmt.Errorf("build merkle tree: %w", err) |
| 106 | + } |
| 107 | + |
| 108 | + // Generate challenge indices — simple deterministic selection using tree root as entropy. |
| 109 | + m := challengeCount |
| 110 | + if m > nc { |
| 111 | + m = nc |
| 112 | + } |
| 113 | + indices := deriveSimpleIndices(tree.Root[:], nc, m) |
| 114 | + |
| 115 | + commitment := &actiontypes.AvailabilityCommitment{ |
| 116 | + CommitmentType: CommitmentType, |
| 117 | + HashAlgo: actiontypes.HashAlgo_HASH_ALGO_BLAKE3, |
| 118 | + ChunkSize: chunkSize, |
| 119 | + TotalSize: uint64(totalSize), |
| 120 | + NumChunks: nc, |
| 121 | + Root: tree.Root[:], |
| 122 | + ChallengeIndices: indices, |
| 123 | + } |
| 124 | + |
| 125 | + return commitment, tree, nil |
| 126 | +} |
| 127 | + |
| 128 | +// GenerateChunkProofs produces Merkle proofs for the challenge indices in the commitment. |
| 129 | +func GenerateChunkProofs(tree *merkle.Tree, indices []uint32) ([]*actiontypes.ChunkProof, error) { |
| 130 | + proofs := make([]*actiontypes.ChunkProof, len(indices)) |
| 131 | + for i, idx := range indices { |
| 132 | + p, err := tree.GenerateProof(int(idx)) |
| 133 | + if err != nil { |
| 134 | + return nil, fmt.Errorf("generate proof for chunk %d: %w", idx, err) |
| 135 | + } |
| 136 | + |
| 137 | + pathHashes := make([][]byte, len(p.PathHashes)) |
| 138 | + for j, h := range p.PathHashes { |
| 139 | + pathHashes[j] = h[:] |
| 140 | + } |
| 141 | + |
| 142 | + proofs[i] = &actiontypes.ChunkProof{ |
| 143 | + ChunkIndex: p.ChunkIndex, |
| 144 | + LeafHash: p.LeafHash[:], |
| 145 | + PathHashes: pathHashes, |
| 146 | + PathDirections: p.PathDirections, |
| 147 | + } |
| 148 | + } |
| 149 | + return proofs, nil |
| 150 | +} |
| 151 | + |
| 152 | +// VerifyCommitmentRoot rebuilds the Merkle tree from a file and checks it matches the on-chain root. |
| 153 | +func VerifyCommitmentRoot(filePath string, commitment *actiontypes.AvailabilityCommitment) (*merkle.Tree, error) { |
| 154 | + if commitment == nil { |
| 155 | + return nil, nil // pre-LEP-5 action, nothing to verify |
| 156 | + } |
| 157 | + |
| 158 | + chunks, err := ChunkFile(filePath, commitment.ChunkSize) |
| 159 | + if err != nil { |
| 160 | + return nil, fmt.Errorf("chunk file for verification: %w", err) |
| 161 | + } |
| 162 | + |
| 163 | + if uint32(len(chunks)) != commitment.NumChunks { |
| 164 | + return nil, fmt.Errorf("chunk count mismatch: got %d, expected %d", len(chunks), commitment.NumChunks) |
| 165 | + } |
| 166 | + |
| 167 | + tree, err := merkle.BuildTree(chunks) |
| 168 | + if err != nil { |
| 169 | + return nil, fmt.Errorf("build merkle tree for verification: %w", err) |
| 170 | + } |
| 171 | + |
| 172 | + if tree.Root != [merkle.HashSize]byte(commitment.Root) { |
| 173 | + return nil, fmt.Errorf("merkle root mismatch: computed %x, expected %x", tree.Root[:], commitment.Root) |
| 174 | + } |
| 175 | + |
| 176 | + return tree, nil |
| 177 | +} |
| 178 | + |
| 179 | +// deriveSimpleIndices generates m unique indices in [0, numChunks) using BLAKE3(root || counter). |
| 180 | +func deriveSimpleIndices(root []byte, numChunks, m uint32) []uint32 { |
| 181 | + if numChunks == 0 || m == 0 { |
| 182 | + return nil |
| 183 | + } |
| 184 | + |
| 185 | + indices := make([]uint32, 0, m) |
| 186 | + used := make(map[uint32]struct{}, m) |
| 187 | + counter := uint32(0) |
| 188 | + |
| 189 | + for uint32(len(indices)) < m { |
| 190 | + // BLAKE3(root || uint32be(counter)) |
| 191 | + buf := make([]byte, len(root)+4) |
| 192 | + copy(buf, root) |
| 193 | + buf[len(root)] = byte(counter >> 24) |
| 194 | + buf[len(root)+1] = byte(counter >> 16) |
| 195 | + buf[len(root)+2] = byte(counter >> 8) |
| 196 | + buf[len(root)+3] = byte(counter) |
| 197 | + |
| 198 | + h := merkle.HashLeaf(counter, buf) // reuse BLAKE3 — domain doesn't matter here |
| 199 | + // Use first 8 bytes as uint64 mod numChunks |
| 200 | + val := uint64(h[0])<<56 | uint64(h[1])<<48 | uint64(h[2])<<40 | uint64(h[3])<<32 | |
| 201 | + uint64(h[4])<<24 | uint64(h[5])<<16 | uint64(h[6])<<8 | uint64(h[7]) |
| 202 | + idx := uint32(val % uint64(numChunks)) |
| 203 | + |
| 204 | + if _, exists := used[idx]; !exists { |
| 205 | + used[idx] = struct{}{} |
| 206 | + indices = append(indices, idx) |
| 207 | + } |
| 208 | + counter++ |
| 209 | + } |
| 210 | + return indices |
| 211 | +} |
0 commit comments