From 14bdab040a2cfd030e1840a75bd2effb0f0b8f60 Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Wed, 4 Nov 2026 12:04:31 +0000 Subject: [PATCH 1/9] llo/keyring: move the LLO onchain keyring from chainlink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the keyring that signs and verifies LLO reports per report format into data-streams, next to the report contexts and codecs it depends on, so a change to how a format is signed ships in one repo. Hash EVMStreamlined reports with go-ethereum Keccak256, which gives the same digest without an error path. Add a test that signs with a real EVM key and recovers the signer from keccak256(digest ‖ report). The ocr2key test dependency adds its key type modules to go.mod as indirect requirements. --- go.mod | 6 ++ go.sum | 12 +++ llo/keyring/keyring.go | 138 ++++++++++++++++++++++++++++++ llo/keyring/keyring_test.go | 166 ++++++++++++++++++++++++++++++++++++ 4 files changed, 322 insertions(+) create mode 100644 llo/keyring/keyring.go create mode 100644 llo/keyring/keyring_test.go diff --git a/go.mod b/go.mod index 6478fa3..d4e390d 100644 --- a/go.mod +++ b/go.mod @@ -34,9 +34,12 @@ require ( ) require ( + filippo.io/edwards25519 v1.1.1 // indirect github.com/DataDog/zstd v1.5.6 // indirect github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/NethermindEth/juno v0.12.5 // indirect + github.com/NethermindEth/starknet.go v0.8.0 // indirect github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260416073033-7c2071eaa8d4 // indirect github.com/VictoriaMetrics/fastcache v1.13.0 // indirect github.com/XSAM/otelsql v0.42.0 // indirect @@ -98,6 +101,7 @@ require ( github.com/hashicorp/go-bexpr v0.1.10 // indirect github.com/hashicorp/go-hclog v1.6.3 // indirect github.com/hashicorp/yamux v0.1.2 // indirect + github.com/hdevalence/ed25519consensus v0.2.0 // indirect github.com/holiman/billy v0.0.0-20250707135307-f2f9b9aae7db // indirect github.com/holiman/bloomfilter/v2 v2.0.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect @@ -141,6 +145,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 // indirect github.com/scylladb/go-reflectx v1.0.1 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect + github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 // indirect github.com/smartcontractkit/chain-selectors v1.0.104 // indirect github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20260915184316-2730f1867c92 // indirect github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20260804191526-b7a850ae7648 // indirect @@ -160,6 +165,7 @@ require ( github.com/wlynxg/anet v0.0.5 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect + github.com/xssnick/tonutils-go v1.14.1 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect github.com/zeebo/xxh3 v1.1.0 // indirect go.mongodb.org/mongo-driver v1.17.9 // indirect diff --git a/go.sum b/go.sum index 14e989e..97147a8 100644 --- a/go.sum +++ b/go.sum @@ -48,6 +48,10 @@ github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAw github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/NethermindEth/juno v0.12.5 h1:a+KYQg8MxzNJIbbqGHq+vU9nTyuWu3acbyXxcUPUDOY= +github.com/NethermindEth/juno v0.12.5/go.mod h1:XonWmZVRwCVHv1gjoVCoTFiZnYObwdukpd3NCsl04bA= +github.com/NethermindEth/starknet.go v0.8.0 h1:mGh7qDWrvuXJPcgGJP31DpifzP6+Ef2gt/BQhaqsV40= +github.com/NethermindEth/starknet.go v0.8.0/go.mod h1:slNA8PxtxA/0LQv0FwHnL3lHFDNhVZfTK6U2gjVb7l8= github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260416073033-7c2071eaa8d4 h1:/97whAzwYxMNHXeTfhAtCRzNCpyblmxCtSYpsfzCszM= github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260416073033-7c2071eaa8d4/go.mod h1:ioLG6R+5bUSO1oeGSDxOV3FADARuMoytZCSX6MEMQkI= github.com/VictoriaMetrics/fastcache v1.13.0 h1:AW4mheMR5Vd9FkAPUv+NH6Nhw+fmbTMGMsNAoA/+4G0= @@ -342,6 +346,8 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= +github.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU= +github.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= github.com/holiman/billy v0.0.0-20250707135307-f2f9b9aae7db h1:IZUYC/xb3giYwBLMnr8d0TGTzPKFGNTCGgGLoyeX330= github.com/holiman/billy v0.0.0-20250707135307-f2f9b9aae7db/go.mod h1:xTEYN9KCHxuYHs+NmrmzFcnvHMzLLNiGFafCb1n3Mfg= github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= @@ -539,6 +545,8 @@ github.com/shurcooL/go v0.0.0-20200502201357-93f07166e636/go.mod h1:TDJrrUr11Vxr github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546/go.mod h1:TrYk7fJVaAttu97ZZKrO9UbRa8izdowaMIZcxYMbVaw= +github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 h1:aQKxg3+2p+IFXXg97McgDGT5zcMrQoi0EICZs8Pgchs= +github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3/go.mod h1:9/etS5gpQq9BJsJMWg1wpLbfuSnkm8dPF6FdW2JXVhA= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/smartcontractkit/chain-selectors v1.0.104 h1:/n9pPGM5W/+r1eHoWZv4VwX9LNS1af4+ICyhM8zKRNM= github.com/smartcontractkit/chain-selectors v1.0.104/go.mod h1:qy7whtgG5g+7z0jt0nRyii9bLND9m15NZTzuQPkMZ5w= @@ -575,6 +583,8 @@ github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stellar/go-stellar-sdk v0.5.0 h1:xpOO+ZTyvGz54wTm7pwl2Gf1e6lZl0ExrJ/tKb+Roj4= github.com/stellar/go-stellar-sdk v0.5.0/go.mod h1:tLKAQPxa2I5UvGMabBbUXcY3fmgYnfDudrMeK7CDX4w= @@ -618,6 +628,8 @@ github.com/xdrpp/goxdr v0.1.1 h1:E1B2c6E8eYhOVyd7yEpOyopzTPirUeF6mVOfXfGyJyc= github.com/xdrpp/goxdr v0.1.1/go.mod h1:dXo1scL/l6s7iME1gxHWo2XCppbHEKZS7m/KyYWkNzA= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= +github.com/xssnick/tonutils-go v1.14.1 h1:zV/iVYl/h3hArS+tPsd9XrSFfGert3r21caMltPSeHg= +github.com/xssnick/tonutils-go v1.14.1/go.mod h1:68xwWjpoGGqiTbLJ0gT63sKu1Z1moCnDLLzA+DKanIg= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= diff --git a/llo/keyring/keyring.go b/llo/keyring/keyring.go new file mode 100644 index 0000000..14c5c40 --- /dev/null +++ b/llo/keyring/keyring.go @@ -0,0 +1,138 @@ +// Package keyring signs and verifies LLO reports with the onchain key for +// each report format. +package keyring + +import ( + "bytes" + "fmt" + "maps" + "slices" + "sort" + + "github.com/ethereum/go-ethereum/crypto" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + "github.com/smartcontractkit/chainlink-data-streams/llo/reportcodec/evm" +) + +type OnchainKeyring ocr3types.OnchainKeyring[llotypes.ReportInfo] + +var _ OnchainKeyring = &onchainKeyring{} + +type Key interface { + // Legacy Sign/Verify methods needed for v0.3 report compatibility + // New keys can leave these stubbed + Sign(reportCtx types.ReportContext, report types.Report) ([]byte, error) + Verify(publicKey types.OnchainPublicKey, reportCtx types.ReportContext, report types.Report, signature []byte) bool + + Sign3(digest types.ConfigDigest, seqNr uint64, r types.Report) (signature []byte, err error) + Verify3(publicKey types.OnchainPublicKey, cd types.ConfigDigest, seqNr uint64, r types.Report, signature []byte) bool + SignBlob(b []byte) (sig []byte, err error) + VerifyBlob(publicKey types.OnchainPublicKey, b, sig []byte) bool + PublicKey() types.OnchainPublicKey + MaxSignatureLength() int +} + +type onchainKeyring struct { + lggr logger.Logger + keys map[llotypes.ReportFormat]Key + donID uint32 +} + +func NewOnchainKeyring(lggr logger.Logger, keys map[llotypes.ReportFormat]Key, donID uint32) OnchainKeyring { + return &onchainKeyring{ + logger.Sugared(lggr).Named("OnchainKeyring"), keys, donID, + } +} + +func (okr *onchainKeyring) PublicKey() types.OnchainPublicKey { + // All unique public keys sorted in ascending order and combined into one + // byte string + onchainPublicKey := []byte{} + + keys := slices.Collect(maps.Values(okr.keys)) + if len(keys) == 0 { + return onchainPublicKey + } + sort.Slice(keys, func(i, j int) bool { + return bytes.Compare(keys[i].PublicKey(), keys[j].PublicKey()) < 0 + }) + + onchainPublicKey = append(onchainPublicKey, keys[0].PublicKey()...) + if len(keys) == 1 { + return onchainPublicKey + } + for i := 1; i < len(keys); i++ { + if keys[i] != keys[i-1] { + onchainPublicKey = append(onchainPublicKey, keys[i].PublicKey()...) + } + } + + return onchainPublicKey +} + +func (okr *onchainKeyring) MaxSignatureLength() (n int) { + // Needs to be max of all chain sigs + for _, k := range okr.keys { + n += k.MaxSignatureLength() + } + return n +} + +func (okr *onchainKeyring) Sign(digest types.ConfigDigest, seqNr uint64, r ocr3types.ReportWithInfo[llotypes.ReportInfo]) (signature []byte, err error) { + rf := r.Info.ReportFormat + switch rf { + case llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr: + if key, exists := okr.keys[rf]; exists { + // NOTE: Must use legacy Sign method for compatibility with v0.3 report verification + rc, err := evm.LegacyReportContext(digest, seqNr, okr.donID) + if err != nil { + return nil, fmt.Errorf("failed to get legacy report context: %w", err) + } + return key.Sign(rc, r.Report) + } + case llotypes.ReportFormatEVMStreamlined: + if key, exists := okr.keys[rf]; exists { + // NOTE: Report context for EVMStreamlined is digest only since + // timestamp is guaranteed unique per round and always included in + // the report + return key.SignBlob(crypto.Keccak256(digest[:], r.Report)) + } + default: + if key, exists := okr.keys[rf]; exists { + return key.Sign3(digest, seqNr, r.Report) + } + } + return nil, fmt.Errorf("Sign failed; unsupported report format: %q", r.Info.ReportFormat) +} + +func (okr *onchainKeyring) Verify(key types.OnchainPublicKey, digest types.ConfigDigest, seqNr uint64, r ocr3types.ReportWithInfo[llotypes.ReportInfo], signature []byte) bool { + rf := r.Info.ReportFormat + switch rf { + case llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr: + if verifier, exists := okr.keys[rf]; exists { + // NOTE: Must use legacy Verify method for compatibility with v0.3 report verification + rc, err := evm.LegacyReportContext(digest, seqNr, okr.donID) + if err != nil { + okr.lggr.Errorw("Verify failed; unable to get legacy report context", "err", err) + return false + } + return verifier.Verify(key, rc, r.Report, signature) + } + case llotypes.ReportFormatEVMStreamlined: + if verifier, exists := okr.keys[rf]; exists { + return verifier.VerifyBlob(key, crypto.Keccak256(digest[:], r.Report), signature) + } + default: + if verifier, exists := okr.keys[rf]; exists { + return verifier.Verify3(key, digest, seqNr, r.Report, signature) + } + } + + okr.lggr.Errorf("Verify failed; unsupported report format: %q", r.Info.ReportFormat) + return false +} diff --git a/llo/keyring/keyring_test.go b/llo/keyring/keyring_test.go new file mode 100644 index 0000000..335dfe8 --- /dev/null +++ b/llo/keyring/keyring_test.go @@ -0,0 +1,166 @@ +package keyring + +import ( + crand "crypto/rand" + "fmt" + "math" + "math/rand/v2" + "testing" + + "github.com/ethereum/go-ethereum/common" + gethcrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + "github.com/smartcontractkit/chainlink-common/keystore/corekeys" + "github.com/smartcontractkit/chainlink-common/keystore/corekeys/ocr2key" + "github.com/smartcontractkit/chainlink-common/pkg/logger" + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" +) + +var _ Key = &mockKey{} + +type mockKey struct { + format llotypes.ReportFormat + verify bool + maxSignatureLen int + sig []byte +} + +func (m *mockKey) Sign(reportCtx types.ReportContext, report types.Report) ([]byte, error) { + return m.sig, nil +} + +func (m *mockKey) Verify(publicKey types.OnchainPublicKey, reportCtx types.ReportContext, report types.Report, signature []byte) bool { + return m.verify +} + +func (m *mockKey) Sign3(digest types.ConfigDigest, seqNr uint64, r types.Report) (signature []byte, err error) { + return m.sig, nil +} + +func (m *mockKey) Verify3(publicKey types.OnchainPublicKey, cd types.ConfigDigest, seqNr uint64, r types.Report, signature []byte) bool { + return m.verify +} +func (m *mockKey) SignBlob(b []byte) (sig []byte, err error) { return m.sig, nil } +func (m *mockKey) VerifyBlob(publicKey types.OnchainPublicKey, b, sig []byte) bool { + return m.verify +} + +func (m *mockKey) PublicKey() types.OnchainPublicKey { + b := make([]byte, m.maxSignatureLen) + for i := range m.maxSignatureLen { + b[i] = byte(255) + } + return types.OnchainPublicKey(b) +} + +func (m *mockKey) MaxSignatureLength() int { + return m.maxSignatureLen +} + +func Test_Keyring(t *testing.T) { + t.Parallel() + lggr := logger.Test(t) + + ks := map[llotypes.ReportFormat]Key{ + llotypes.ReportFormatEVMPremiumLegacy: &mockKey{format: llotypes.ReportFormatEVMPremiumLegacy, maxSignatureLen: 1, sig: []byte("sig-1")}, + llotypes.ReportFormatJSON: &mockKey{format: llotypes.ReportFormatJSON, maxSignatureLen: 2, sig: []byte("sig-2")}, + llotypes.ReportFormatEVMStreamlined: &mockKey{format: llotypes.ReportFormatEVMStreamlined, maxSignatureLen: 6, sig: []byte("sig-6")}, + } + + kr := NewOnchainKeyring(lggr, ks, 2) + + cases := []struct { + format llotypes.ReportFormat + }{ + { + llotypes.ReportFormatEVMPremiumLegacy, + }, + { + llotypes.ReportFormatJSON, + }, + { + llotypes.ReportFormatEVMStreamlined, + }, + } + + cd, err := types.BytesToConfigDigest(mustRandBytes(32)) + require.NoError(t, err) + seqNr := rand.Uint64N(math.MaxUint32 << 8) + t.Run("Sign+Verify", func(t *testing.T) { + t.Parallel() + for _, tc := range cases { + t.Run(tc.format.String(), func(t *testing.T) { + t.Parallel() + ksLocal := map[llotypes.ReportFormat]Key{ + llotypes.ReportFormatEVMPremiumLegacy: &mockKey{format: llotypes.ReportFormatEVMPremiumLegacy, maxSignatureLen: 1, sig: []byte("sig-1")}, + llotypes.ReportFormatJSON: &mockKey{format: llotypes.ReportFormatJSON, maxSignatureLen: 2, sig: []byte("sig-2")}, + llotypes.ReportFormatEVMStreamlined: &mockKey{format: llotypes.ReportFormatEVMStreamlined, maxSignatureLen: 6, sig: []byte("sig-6")}, + } + krLocal := NewOnchainKeyring(lggr, ksLocal, 2) + k := ksLocal[tc.format] + + sig, err := krLocal.Sign(cd, seqNr, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Info: llotypes.ReportInfo{ReportFormat: tc.format}}) + require.NoError(t, err) + + assert.Equal(t, fmt.Appendf(nil, "sig-%d", tc.format), sig) + + assert.False(t, krLocal.Verify(nil, cd, seqNr, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Info: llotypes.ReportInfo{ReportFormat: tc.format}}, sig)) + + k.(*mockKey).verify = true + }) + } + }) + + t.Run("MaxSignatureLength", func(t *testing.T) { + t.Parallel() + assert.Equal(t, 6+2+1, kr.MaxSignatureLength()) + }) + t.Run("PublicKey", func(t *testing.T) { + t.Parallel() + b := make([]byte, 6+2+1) + for i := range b { + b[i] = byte(255) + } + assert.Equal(t, types.OnchainPublicKey(b), kr.PublicKey()) + }) +} + +func Test_Keyring_EVMStreamlined(t *testing.T) { + t.Parallel() + kb := ocr2key.MustNewInsecure(crand.Reader, corekeys.EVM) + kr := NewOnchainKeyring(logger.Test(t), map[llotypes.ReportFormat]Key{llotypes.ReportFormatEVMStreamlined: kb}, 2) + + cd, err := types.BytesToConfigDigest(mustRandBytes(32)) + require.NoError(t, err) + report := ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: mustRandBytes(64), + Info: llotypes.ReportInfo{ReportFormat: llotypes.ReportFormatEVMStreamlined}, + } + + sig, err := kr.Sign(cd, 42, report) + require.NoError(t, err) + require.True(t, kr.Verify(kb.PublicKey(), cd, 42, report, sig)) + + // An onchain verifier recovers the signer from keccak256(digest ‖ report). + h := gethcrypto.Keccak256(append(cd[:], report.Report...)) + recovered, err := gethcrypto.SigToPub(h, sig) + require.NoError(t, err) + assert.Equal(t, common.BytesToAddress(kb.PublicKey()), gethcrypto.PubkeyToAddress(*recovered)) + + report.Report = mustRandBytes(64) + assert.False(t, kr.Verify(kb.PublicKey(), cd, 42, report, sig)) +} + +func mustRandBytes(n int) (b []byte) { + b = make([]byte, n) + _, err := crand.Read(b) + if err != nil { + panic(err) + } + return b +} From 67f577cf1b6b3a39fb4d17c276057b7355e69dd6 Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Wed, 4 Nov 2026 12:34:48 +0000 Subject: [PATCH 2/9] llo/dev/v31: sign Merkle channel reports as one bundle root per round Add the Merkle tree, bundle and delivery codecs with golden vectors, and the signingScheme channel field. The empty scheme is left out of the proto, so channel hashes do not change. v31 groups the reports of Merkle channels into one bundle per signing family per round, split by size, and emits it ahead of the staging marker. Backfill reports follow the scheme of their target channel. The keyring signs the bundle root once with SignBlob under the family the bundle carries, and rejects a bundle whose family differs from its report format. Bundle roots are cached by bundle hash, since libocr verifies every peer signature over the same bundle. The transmitter expands each bundle into one delivery per leaf and queues them in a single commit channel send through dataengine.TransmitBatch. Add the EVM delivery packer. v30 does not vote for channels that set a signing scheme. --- llo/dev/v31/doc.go | 35 ++ llo/dev/v31/merkle.go | 97 ++++ llo/dev/v31/merkle_test.go | 170 +++++++ llo/dev/v31/reports.go | 29 ++ llo/keyring/keyring.go | 103 ++++- llo/keyring/keyring_test.go | 101 +++++ llo/protocol/channel_definitions.go | 6 + llo/protocol/channel_definitions_test.go | 26 ++ llo/protocol/channel_hash_test.go | 6 + llo/protocol/conv.go | 2 + llo/protocol/generate.go | 1 + llo/protocol/history_backfill.go | 7 +- llo/protocol/llo_merkle.pb.go | 294 ++++++++++++ llo/protocol/llo_merkle.proto | 41 ++ llo/protocol/merkle.go | 343 ++++++++++++++ llo/protocol/merkle_test.go | 427 ++++++++++++++++++ llo/protocol/plugin_codecs.pb.go | 20 +- llo/protocol/plugin_codecs.proto | 4 + .../fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 | 5 + llo/protocol/time_resolution.go | 2 +- llo/protocol/time_resolution_test.go | 1 + .../evm/report_codec_evm_merkle.go | 99 ++++ .../evm/report_codec_evm_merkle_test.go | 129 ++++++ .../evm/report_codec_premium_legacy.go | 35 +- llo/transmitter/dataengine/server.go | 4 + .../dataengine/server_merkle_test.go | 98 ++++ llo/transmitter/dataengine/transmitter.go | 50 +- llo/transmitter/transmitter.go | 65 +++ llo/transmitter/transmitter_merkle_test.go | 131 ++++++ llo/v30/plugin_codecs_test.go | 2 + llo/v30/plugin_observation.go | 35 +- llo/v30/plugin_test.go | 20 + 32 files changed, 2356 insertions(+), 32 deletions(-) create mode 100644 llo/dev/v31/merkle.go create mode 100644 llo/dev/v31/merkle_test.go create mode 100644 llo/protocol/llo_merkle.pb.go create mode 100644 llo/protocol/llo_merkle.proto create mode 100644 llo/protocol/merkle.go create mode 100644 llo/protocol/merkle_test.go create mode 100644 llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 create mode 100644 llo/reportcodec/evm/report_codec_evm_merkle.go create mode 100644 llo/reportcodec/evm/report_codec_evm_merkle_test.go create mode 100644 llo/transmitter/dataengine/server_merkle_test.go create mode 100644 llo/transmitter/transmitter_merkle_test.go diff --git a/llo/dev/v31/doc.go b/llo/dev/v31/doc.go index 5e1f9eb..7e68c42 100644 --- a/llo/dev/v31/doc.go +++ b/llo/dev/v31/doc.go @@ -199,6 +199,41 @@ // EffectiveStreams drops any such inline entries before appending the declared // ones, so it reads definitions written by either version identically. // +// # Merkle batched report signing +// +// A channel with SigningScheme "merkle" is not signed one report at a time. +// Reports puts the reports of all such channels into one bundle per signing +// family (merkle.go), after the per report channels and before the staging +// marker, split by size to fit MaxReportBytes. The keyring signs the bundle's +// Merkle root once, and the transmitter expands the attested bundle into one +// delivery per channel with its proof. See protocol/merkle.go for the tree and +// the signed message. +// +// The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers every +// format in llo/reportcodec/evm. Backfill reports follow the scheme of their +// target channel. +// +// A family is not tied to a destination chain. It fixes one signing key, one +// hash and signature scheme, and one delivery packer. The root is signed once +// with keys[family], so every member format must accept that signer. The EVM +// family hashes with keccak256, signs with SignBlob over secp256k1 for +// ecrecover, and packs deliveries with ReportCodecEVMMerkle. A format on +// another key type needs its own family, since one signature cannot cover two +// keys. Adding a family is a family constant, a protocol.MerkleFamily mapping, +// a keyring case and a packer. Leaves commit to their member format and the +// signed message to its family, so the bundle, tree and proof formats do not +// change. +// +// The family is a report format rather than a signing scheme field on +// ReportInfo so that a bundle of mixed codecs has a single format to select its +// key, and so the transmit queue and TransmitRequest recognise deliveries by +// report_format without a schema or wire change. +// +// There is no protocol version gate. A build that predates the field drops it +// and votes a different channel hash, so set the scheme only once every oracle +// runs a build that knows it. v3.0 does not support the scheme and never votes +// for a channel that sets it. +// // # Stream history // // Expressions can read a window of a stream's past agreed values with diff --git a/llo/dev/v31/merkle.go b/llo/dev/v31/merkle.go new file mode 100644 index 0000000..0818afa --- /dev/null +++ b/llo/dev/v31/merkle.go @@ -0,0 +1,97 @@ +package llo + +import ( + "fmt" + "slices" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" +) + +// merkleBundleMaxBytes is the MaxReportBytes NewReportingPlugin declares. A +// bundle is one report, so it must fit in it. +const merkleBundleMaxBytes = ocr3_1types.MaxMaxReportBytes + +// merkleBundler collects the channel reports of a round that are signed as +// leaves, per signing family. +type merkleBundler struct { + leaves map[llotypes.ReportFormat][]*protocol.LLOMerkleLeafProto + // sources are the reportable channels the leaves were emitted for, in leaf + // order. It differs from the leaf channel ID for backfill reports. + sources map[llotypes.ReportFormat][]llotypes.ChannelID +} + +// add records the report encoded for channelID in format as a leaf of family. +func (b *merkleBundler) add(family llotypes.ReportFormat, source, channelID llotypes.ChannelID, format llotypes.ReportFormat, report []byte) { + if b.leaves == nil { + b.leaves = map[llotypes.ReportFormat][]*protocol.LLOMerkleLeafProto{} + b.sources = map[llotypes.ReportFormat][]llotypes.ChannelID{} + } + b.leaves[family] = append(b.leaves[family], &protocol.LLOMerkleLeafProto{ + ChannelID: channelID, + ReportFormat: uint32(format), + Report: report, + }) + b.sources[family] = append(b.sources[family], source) +} + +// signingFamily decides how the report of a channel encoded with cd is signed. +// It returns the family when the report is a leaf, and false when it is signed +// on its own. A scheme the instance cannot sign with returns an error and the +// report is not emitted. +// +// Baseline verification keeps such a scheme out of the committed set. The +// error path only guards against it getting there anyway. +func (p *Plugin) signingFamily(cd llotypes.ChannelDefinition) (llotypes.ReportFormat, bool, error) { + switch cd.SigningScheme { + case llotypes.SigningSchemeDefault: + return 0, false, nil + case llotypes.SigningSchemeMerkle: + family, ok := protocol.MerkleFamily(cd.ReportFormat) + if !ok { + return 0, false, fmt.Errorf("report format %s has no signing family", cd.ReportFormat) + } + return family, true, nil + default: + return 0, false, fmt.Errorf("unknown signing scheme %q", cd.SigningScheme) + } +} + +// bundles returns one bundle report per family, split by size, in family +// order. Leaves are in the order they were added, which is ascending +// reportable channel ID. +func (b *merkleBundler) bundles(p *Plugin, seqNr uint64, stage llotypes.LifeCycleStage) ([]ocr3types.ReportPlus[llotypes.ReportInfo], error) { + families := make([]llotypes.ReportFormat, 0, len(b.leaves)) + for family := range b.leaves { + families = append(families, family) + } + slices.Sort(families) + + var rwis []ocr3types.ReportPlus[llotypes.ReportInfo] + for _, family := range families { + encoded, oversized, err := protocol.SplitMerkleBundle(family, b.leaves[family], merkleBundleMaxBytes) + if err != nil { + return nil, fmt.Errorf("error encoding %s bundle: %w", family, err) + } + for _, i := range oversized { + leaf := b.leaves[family][i] + p.reportNotEmitted(seqNr, b.sources[family][i], llotypes.ReportFormat(leaf.ReportFormat), "merkle_leaf_too_large", "reportBytes", len(leaf.Report)) + } + for _, bundle := range encoded { + rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ + ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: bundle, + Info: llotypes.ReportInfo{ + LifeCycleStage: stage, + ReportFormat: family, + }, + }, + }) + } + } + return rwis, nil +} diff --git a/llo/dev/v31/merkle_test.go b/llo/dev/v31/merkle_test.go new file mode 100644 index 0000000..ce8d104 --- /dev/null +++ b/llo/dev/v31/merkle_test.go @@ -0,0 +1,170 @@ +package llo + +import ( + "fmt" + "testing" + + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" + "github.com/smartcontractkit/chainlink-data-streams/llo/reportcodec" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" +) + +// leafCodec encodes a report as its format and channel ID, or as size bytes +// when size is set, so a test can tell reports apart and control their size. +type leafCodec struct{ size int } + +func (c leafCodec) Encode(r protocol.Report, cd llotypes.ChannelDefinition, _ *protocol.OptsCache) ([]byte, error) { + if c.size > 0 { + b := make([]byte, c.size) + b[0] = byte(r.ChannelID) + return b, nil + } + return fmt.Appendf(nil, "%s:%d", cd.ReportFormat, r.ChannelID), nil +} + +func (leafCodec) Verify(llotypes.ChannelDefinition) error { return nil } + +func merklePlugin(t *testing.T, codec leafCodec) *Plugin { + p := testPlugin(t) + p.ReportCodecs = map[llotypes.ReportFormat]protocol.ReportCodec{ + llotypes.ReportFormatJSON: reportcodec.JSONReportCodec{}, + llotypes.ReportFormatEVMABIEncodeUnpacked: codec, + llotypes.ReportFormatEVMStreamlined: codec, + llotypes.ReportFormatEVMPremiumLegacy: codec, + llotypes.ReportFormatEVMABIEncodeUnpackedExpr: codec, + } + return p +} + +func merkleChannel(format llotypes.ReportFormat, scheme llotypes.SigningScheme) llotypes.ChannelDefinition { + return llotypes.ChannelDefinition{ + ReportFormat: format, + Streams: []llotypes.Stream{{StreamID: 100, Aggregator: llotypes.AggregatorMedian}}, + SigningScheme: scheme, + } +} + +// merklePrecursor is a round in which every channel of defs is reportable. +func merklePrecursor(t *testing.T, stage llotypes.LifeCycleStage, defs llotypes.ChannelDefinitions) []byte { + t.Helper() + ids := make([]llotypes.ChannelID, 0, len(defs)) + validAfter := map[llotypes.ChannelID]uint64{} + for id := range defs { + ids = append(ids, id) + validAfter[id] = 1_000_000_000 + } + sortChannelIDs(ids) + prec, err := encodePrecursor(precursor{ + LifeCycleStage: stage, + ObservationTimestampNanoseconds: 2_000_000_000, + ChannelDefinitions: defs, + ChannelStateSeqNr: 2, + ValidAfterNanoseconds: validAfter, + StreamAggregates: protocol.StreamAggregates{ + 100: {llotypes.AggregatorMedian: protocol.ToDecimal(decimal.NewFromInt(1))}, + }, + ReportableChannelIDs: ids, + }) + require.NoError(t, err) + return prec +} + +func bundleOf(t *testing.T, rwi ocr3types.ReportPlus[llotypes.ReportInfo]) *protocol.LLOMerkleBundleProto { + t.Helper() + require.Equal(t, llotypes.ReportFormatEVMMerkle, rwi.ReportWithInfo.Info.ReportFormat) + bundle, err := protocol.DecodeMerkleBundle(rwi.ReportWithInfo.Report) + require.NoError(t, err) + return bundle +} + +func Test_Reports_MerkleBundle(t *testing.T) { + ctx := t.Context() + defs := llotypes.ChannelDefinitions{ + 1: merkleChannel(llotypes.ReportFormatJSON, llotypes.SigningSchemeDefault), + 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), + 4: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeDefault), + 5: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), + } + + t.Run("merkle channels are bundled after the per report channels", func(t *testing.T) { + p := merklePlugin(t, leafCodec{}) + rwis, err := p.Reports(ctx, 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) + require.NoError(t, err) + require.Len(t, rwis, 3) + + assert.Equal(t, llotypes.ReportFormatJSON, rwis[0].ReportWithInfo.Info.ReportFormat) + assert.Equal(t, llotypes.ReportFormat(llotypes.ReportFormatEVMABIEncodeUnpacked), rwis[1].ReportWithInfo.Info.ReportFormat) + assert.Equal(t, "evm_abi_encode_unpacked:4", string(rwis[1].ReportWithInfo.Report)) + + assert.Equal(t, protocol.LifeCycleStageProduction, rwis[2].ReportWithInfo.Info.LifeCycleStage) + bundle := bundleOf(t, rwis[2]) + require.Len(t, bundle.Leaves, 3) + for i, want := range []struct { + id llotypes.ChannelID + format llotypes.ReportFormat + }{ + {2, llotypes.ReportFormatEVMABIEncodeUnpacked}, + {3, llotypes.ReportFormatEVMStreamlined}, + {5, llotypes.ReportFormatEVMPremiumLegacy}, + } { + leaf := bundle.Leaves[i] + assert.Equal(t, want.id, leaf.ChannelID) + assert.Equal(t, uint32(want.format), leaf.ReportFormat) + assert.Equal(t, fmt.Sprintf("%s:%d", want.format, want.id), string(leaf.Report)) + } + + // Every oracle builds the same bundle bytes from the same precursor. + again, err := merklePlugin(t, leafCodec{}).Reports(ctx, 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) + require.NoError(t, err) + assert.Equal(t, rwis[2].ReportWithInfo.Report, again[2].ReportWithInfo.Report) + }) + + t.Run("the staging marker stays last", func(t *testing.T) { + p := merklePlugin(t, leafCodec{}) + rwis, err := p.Reports(ctx, 3, merklePrecursor(t, protocol.LifeCycleStageStaging, defs)) + require.NoError(t, err) + require.Len(t, rwis, 4) + assert.Equal(t, protocol.LifeCycleStageStaging, rwis[2].ReportWithInfo.Info.LifeCycleStage) + bundleOf(t, rwis[2]) + assert.True(t, protocol.IsStagingMarker(rwis[3].ReportWithInfo.Info, rwis[3].ReportWithInfo.Report)) + }) + + t.Run("an unknown scheme is not emitted", func(t *testing.T) { + p := merklePlugin(t, leafCodec{}) + rwis, err := p.Reports(ctx, 3, merklePrecursor(t, protocol.LifeCycleStageProduction, llotypes.ChannelDefinitions{ + 1: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, "both"), + })) + require.NoError(t, err) + assert.Empty(t, rwis) + }) +} + +func Test_Reports_MerkleBundleSplitsBySize(t *testing.T) { + // Three reports of 40% of the report size limit fit two to a bundle. + p := merklePlugin(t, leafCodec{size: merkleBundleMaxBytes * 4 / 10}) + defs := llotypes.ChannelDefinitions{ + 1: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), + 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), + } + rwis, err := p.Reports(t.Context(), 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) + require.NoError(t, err) + require.Len(t, rwis, 2) + + var ids []llotypes.ChannelID + for _, rwi := range rwis { + assert.LessOrEqual(t, len(rwi.ReportWithInfo.Report), merkleBundleMaxBytes) + for _, leaf := range bundleOf(t, rwi).Leaves { + ids = append(ids, leaf.ChannelID) + } + } + assert.Equal(t, []llotypes.ChannelID{1, 2, 3}, ids) +} diff --git a/llo/dev/v31/reports.go b/llo/dev/v31/reports.go index 95d3ad1..e66f387 100644 --- a/llo/dev/v31/reports.go +++ b/llo/dev/v31/reports.go @@ -39,6 +39,9 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t channelOpts := gen.Opts() rwis := []ocr3types.ReportPlus[llotypes.ReportInfo]{} + // Reports of channels signed as Merkle leaves are collected here and + // emitted as one bundle per signing family after the loop. + var bundler merkleBundler if out.LifeCycleStage == protocol.LifeCycleStageRetired { // Emit a retirement report to hand over ValidAfterNanoseconds for a gapless handover. @@ -120,6 +123,17 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t p.reportNotEmitted(seqNr, cid, targetCD.ReportFormat, "encode_failed", "targetChannelID", opts.TargetChannelID, "err", err) continue } + // The backfill report is signed like the target channel's own + // reports, so its consumers verify both the same way. + family, leaf, err := p.signingFamily(targetCD) + if err != nil { + p.reportNotEmitted(seqNr, cid, targetCD.ReportFormat, "signing_scheme_unsupported", "targetChannelID", opts.TargetChannelID, "err", err) + continue + } + if leaf { + bundler.add(family, cid, opts.TargetChannelID, targetCD.ReportFormat, encoded) + continue + } rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -165,6 +179,15 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t p.reportNotEmitted(seqNr, cid, cd.ReportFormat, "encode_failed", "err", encErr) continue } + family, leaf, err := p.signingFamily(cd) + if err != nil { + p.reportNotEmitted(seqNr, cid, cd.ReportFormat, "signing_scheme_unsupported", "err", err) + continue + } + if leaf { + bundler.add(family, cid, cid, cd.ReportFormat, encoded) + continue + } rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -176,6 +199,12 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t }) } + bundles, err := bundler.bundles(p, seqNr, out.LifeCycleStage) + if err != nil { + return nil, err + } + rwis = append(rwis, bundles...) + // The staging marker goes last, so the other reports keep their positions, // and only within the report count limit. if out.LifeCycleStage == protocol.LifeCycleStageStaging && len(rwis) < protocol.MaxReportCount { diff --git a/llo/keyring/keyring.go b/llo/keyring/keyring.go index 14c5c40..51ad6b4 100644 --- a/llo/keyring/keyring.go +++ b/llo/keyring/keyring.go @@ -4,10 +4,12 @@ package keyring import ( "bytes" + "crypto/sha256" "fmt" "maps" "slices" "sort" + "sync" "github.com/ethereum/go-ethereum/crypto" @@ -16,6 +18,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" "github.com/smartcontractkit/chainlink-data-streams/llo/reportcodec/evm" ) @@ -38,14 +41,15 @@ type Key interface { } type onchainKeyring struct { - lggr logger.Logger - keys map[llotypes.ReportFormat]Key - donID uint32 + lggr logger.Logger + keys map[llotypes.ReportFormat]Key + donID uint32 + merkleRoots *merkleRootCache } func NewOnchainKeyring(lggr logger.Logger, keys map[llotypes.ReportFormat]Key, donID uint32) OnchainKeyring { return &onchainKeyring{ - logger.Sugared(lggr).Named("OnchainKeyring"), keys, donID, + logger.Sugared(lggr).Named("OnchainKeyring"), keys, donID, newMerkleRootCache(merkleRootCacheSize), } } @@ -102,6 +106,16 @@ func (okr *onchainKeyring) Sign(digest types.ConfigDigest, seqNr uint64, r ocr3t // the report return key.SignBlob(crypto.Keccak256(digest[:], r.Report)) } + case llotypes.ReportFormatEVMMerkle: + if key, exists := okr.keys[rf]; exists { + // The bundle root is signed once for every channel report it + // covers. The transmitter hands each one out with its proof. + msg, err := okr.merkleSigningMessage(digest, seqNr, r) + if err != nil { + return nil, fmt.Errorf("Sign failed; invalid merkle bundle: %w", err) + } + return key.SignBlob(msg[:]) + } default: if key, exists := okr.keys[rf]; exists { return key.Sign3(digest, seqNr, r.Report) @@ -127,6 +141,15 @@ func (okr *onchainKeyring) Verify(key types.OnchainPublicKey, digest types.Confi if verifier, exists := okr.keys[rf]; exists { return verifier.VerifyBlob(key, crypto.Keccak256(digest[:], r.Report), signature) } + case llotypes.ReportFormatEVMMerkle: + if verifier, exists := okr.keys[rf]; exists { + msg, err := okr.merkleSigningMessage(digest, seqNr, r) + if err != nil { + okr.lggr.Errorw("Verify failed; invalid merkle bundle", "err", err) + return false + } + return verifier.VerifyBlob(key, msg[:], signature) + } default: if verifier, exists := okr.keys[rf]; exists { return verifier.Verify3(key, digest, seqNr, r.Report, signature) @@ -136,3 +159,75 @@ func (okr *onchainKeyring) Verify(key types.OnchainPublicKey, digest types.Confi okr.lggr.Errorf("Verify failed; unsupported report format: %q", r.Info.ReportFormat) return false } + +// merkleSigningMessage returns the message signed for a bundle report. The +// root is recomputed from the leaves, never taken from the report, so a +// signature always covers exactly the leaves it was made over. The family is +// the bundle's, and must match the report format the keyring dispatched on. +func (okr *onchainKeyring) merkleSigningMessage(digest types.ConfigDigest, seqNr uint64, r ocr3types.ReportWithInfo[llotypes.ReportInfo]) (protocol.MerkleHash, error) { + root, err := okr.merkleRoots.root(r.Report) + if err != nil { + return protocol.MerkleHash{}, err + } + if root.family != r.Info.ReportFormat { + return protocol.MerkleHash{}, fmt.Errorf("bundle family %s does not match report format %s", root.family, r.Info.ReportFormat) + } + return protocol.MerkleSigningMessage(digest, seqNr, root.family, root.leafCount, root.root), nil +} + +// merkleRootCacheSize bounds the bundle roots the keyring remembers. libocr +// verifies every peer's signature over the same bundle, so a few recent +// rounds are enough to compute each root once. +const merkleRootCacheSize = 64 + +// merkleRootCache memoizes bundle roots by the hash of the bundle bytes. +type merkleRootCache struct { + mu sync.Mutex + size int + entries map[[32]byte]merkleRoot + order [][32]byte +} + +type merkleRoot struct { + family llotypes.ReportFormat + root protocol.MerkleHash + leafCount uint32 +} + +func newMerkleRootCache(size int) *merkleRootCache { + return &merkleRootCache{size: size, entries: make(map[[32]byte]merkleRoot, size)} +} + +// root decodes the bundle and returns its family, root and leaf count, from +// the cache when the same bytes were seen before. +func (c *merkleRootCache) root(bundle []byte) (merkleRoot, error) { + key := sha256.Sum256(bundle) + c.mu.Lock() + cached, ok := c.entries[key] + c.mu.Unlock() + if ok { + return cached, nil + } + + decoded, err := protocol.DecodeMerkleBundle(bundle) + if err != nil { + return merkleRoot{}, err + } + root, err := protocol.MerkleBundleRoot(decoded) + if err != nil { + return merkleRoot{}, err + } + entry := merkleRoot{family: llotypes.ReportFormat(decoded.Family), root: root, leafCount: uint32(len(decoded.Leaves))} //nolint:gosec // bounded by protocol.MaxMerkleBundleLeaves on decode + + c.mu.Lock() + defer c.mu.Unlock() + if _, ok := c.entries[key]; !ok { + if len(c.order) == c.size { + delete(c.entries, c.order[0]) + c.order = c.order[1:] + } + c.entries[key] = entry + c.order = append(c.order, key) + } + return entry, nil +} diff --git a/llo/keyring/keyring_test.go b/llo/keyring/keyring_test.go index 335dfe8..5b969cb 100644 --- a/llo/keyring/keyring_test.go +++ b/llo/keyring/keyring_test.go @@ -2,6 +2,7 @@ package keyring import ( crand "crypto/rand" + "crypto/sha256" "fmt" "math" "math/rand/v2" @@ -11,6 +12,7 @@ import ( gethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" @@ -19,6 +21,7 @@ import ( "github.com/smartcontractkit/chainlink-common/keystore/corekeys/ocr2key" "github.com/smartcontractkit/chainlink-common/pkg/logger" llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" ) var _ Key = &mockKey{} @@ -164,3 +167,101 @@ func mustRandBytes(n int) (b []byte) { } return b } + +func Test_Keyring_EVMMerkle(t *testing.T) { + t.Parallel() + lggr := logger.Test(t) + newKeyring := func() (OnchainKeyring, ocr2key.KeyBundle) { + kb := ocr2key.MustNewInsecure(crand.Reader, corekeys.EVM) + return NewOnchainKeyring(lggr, map[llotypes.ReportFormat]Key{llotypes.ReportFormatEVMMerkle: kb}, 2), kb + } + signer, signerKey := newKeyring() + verifier, _ := newKeyring() + + bundle := &protocol.LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*protocol.LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, + {ChannelID: 3, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte("three")}, + }, + } + encoded, err := protocol.EncodeMerkleBundle(bundle) + require.NoError(t, err) + report := ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: llotypes.ReportInfo{ReportFormat: llotypes.ReportFormatEVMMerkle}} + cd, err := types.BytesToConfigDigest(mustRandBytes(32)) + require.NoError(t, err) + seqNr := uint64(42) + + sig, err := signer.Sign(cd, seqNr, report) + require.NoError(t, err) + pub := signerKey.PublicKey() + + t.Run("verifies", func(t *testing.T) { + require.True(t, verifier.Verify(pub, cd, seqNr, report, sig)) + // The second check is served from the root cache. + require.True(t, verifier.Verify(pub, cd, seqNr, report, sig)) + }) + + t.Run("signs the merkle message an onchain verifier recovers", func(t *testing.T) { + root, err := protocol.MerkleBundleRoot(bundle) + require.NoError(t, err) + msg := protocol.MerkleSigningMessage(cd, seqNr, llotypes.ReportFormatEVMMerkle, uint32(len(bundle.Leaves)), root) + recovered, err := gethcrypto.SigToPub(msg[:], sig) + require.NoError(t, err) + assert.Equal(t, common.BytesToAddress(pub), gethcrypto.PubkeyToAddress(*recovered)) + }) + + t.Run("rejects another round or configuration", func(t *testing.T) { + assert.False(t, verifier.Verify(pub, cd, seqNr+1, report, sig)) + otherCD := cd + otherCD[0] ^= 1 + assert.False(t, verifier.Verify(pub, otherCD, seqNr, report, sig)) + }) + + t.Run("rejects a bundle whose leaves differ from the signed ones", func(t *testing.T) { + changed := proto.Clone(bundle).(*protocol.LLOMerkleBundleProto) + changed.Leaves[1].Report = []byte("TWO") + b, err := protocol.EncodeMerkleBundle(changed) + require.NoError(t, err) + assert.False(t, verifier.Verify(pub, cd, seqNr, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: b, Info: report.Info}, sig)) + + dropped := proto.Clone(bundle).(*protocol.LLOMerkleBundleProto) + dropped.Leaves = dropped.Leaves[:2] + b, err = protocol.EncodeMerkleBundle(dropped) + require.NoError(t, err) + assert.False(t, verifier.Verify(pub, cd, seqNr, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: b, Info: report.Info}, sig)) + }) + + t.Run("rejects an invalid bundle", func(t *testing.T) { + invalid := ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: []byte{0xff}, Info: report.Info} + _, err := signer.Sign(cd, seqNr, invalid) + require.ErrorContains(t, err, "Sign failed; invalid merkle bundle") + assert.False(t, verifier.Verify(pub, cd, seqNr, invalid, sig)) + }) + + t.Run("rejects a bundle under another report format", func(t *testing.T) { + other := ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: llotypes.ReportInfo{ReportFormat: llotypes.ReportFormatEVMStreamlined}} + _, err := signer.(*onchainKeyring).merkleSigningMessage(cd, seqNr, other) + require.EqualError(t, err, "bundle family evm_merkle does not match report format evm_streamlined") + }) +} + +func Test_merkleRootCache_Evicts(t *testing.T) { + t.Parallel() + c := newMerkleRootCache(2) + bundles := make([][]byte, 3) + for i := range bundles { + b, err := protocol.EncodeMerkleBundle(&protocol.LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*protocol.LLOMerkleLeafProto{{ChannelID: uint32(i + 1), ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined)}}, //nolint:gosec // test + }) + require.NoError(t, err) + bundles[i] = b + _, err = c.root(b) + require.NoError(t, err) + } + assert.Len(t, c.entries, 2) + assert.Len(t, c.order, 2) + assert.NotContains(t, c.entries, sha256.Sum256(bundles[0])) +} diff --git a/llo/protocol/channel_definitions.go b/llo/protocol/channel_definitions.go index 5765c80..2dab5ec 100644 --- a/llo/protocol/channel_definitions.go +++ b/llo/protocol/channel_definitions.go @@ -328,6 +328,12 @@ func analyzeChannelDefinitions(codecs map[llotypes.ReportFormat]ReportCodec, cha continue } + // A signing scheme this build cannot sign with stops the channel from + // reporting, wherever it came from. + if err := VerifySigningScheme(cd); err != nil { + base(fmt.Errorf("invalid ChannelDefinition with ID %d: %w", channelID, err), channelID) + } + if len(cd.Streams) == 0 { base(fmt.Errorf("ChannelDefinition with ID %d has no streams", channelID), channelID) continue diff --git a/llo/protocol/channel_definitions_test.go b/llo/protocol/channel_definitions_test.go index f662d68..fee6b0e 100644 --- a/llo/protocol/channel_definitions_test.go +++ b/llo/protocol/channel_definitions_test.go @@ -54,6 +54,32 @@ func Test_VerifyChannelDefinitions(t *testing.T) { require.EqualError(t, err, "ChannelDefinition with ID 1 has no streams") }) + t.Run("fails for channel with an unsupported signing scheme", func(t *testing.T) { + streams := []llotypes.Stream{{StreamID: 1, Aggregator: llotypes.AggregatorMedian}} + require.NoError(t, VerifyChannelDefinitions(codecs, llotypes.ChannelDefinitions{ + 1: {ReportFormat: mockReportFormat, Streams: streams}, + })) + + err := VerifyChannelDefinitions(codecs, llotypes.ChannelDefinitions{ + 1: {ReportFormat: mockReportFormat, Streams: streams, SigningScheme: llotypes.SigningSchemeMerkle}, + }) + require.EqualError(t, err, `invalid ChannelDefinition with ID 1: signing scheme "merkle" is not supported for report format unknown(0)`) + + err = VerifyChannelDefinitions(codecs, llotypes.ChannelDefinitions{ + 1: {ReportFormat: mockReportFormat, Streams: streams, SigningScheme: "both"}, + }) + require.EqualError(t, err, `invalid ChannelDefinition with ID 1: unknown signing scheme "both"`) + + // Baseline: a committed channel with it is attributed, not rejected + // as a whole. + ids, err := UnverifiableChannelIDs(codecs, llotypes.ChannelDefinitions{ + 1: {ReportFormat: mockReportFormat, Streams: streams, SigningScheme: "both"}, + 2: {ReportFormat: mockReportFormat, Streams: streams}, + }) + require.NoError(t, err) + require.Equal(t, map[llotypes.ChannelID]struct{}{1: {}}, ids) + }) + t.Run("fails for channel with zero aggregator", func(t *testing.T) { channelDefs := llotypes.ChannelDefinitions{ 1: llotypes.ChannelDefinition{ diff --git a/llo/protocol/channel_hash_test.go b/llo/protocol/channel_hash_test.go index b4f9f9e..5f84e6f 100644 --- a/llo/protocol/channel_hash_test.go +++ b/llo/protocol/channel_hash_test.go @@ -42,6 +42,11 @@ func Test_ChannelHashV2(t *testing.T) { }, } assert.Equal(t, "7453e6ac62c0a38ec6f08b5e86adbf3450491be64582ceb9edaf0bbe3213c2d5", fmt.Sprintf("%x", ChannelHashV2(full))) + + // An empty signing scheme is omitted from the encoding, so the hashes + // above predate the field and still hold. + full.SigningScheme = llotypes.SigningSchemeMerkle + assert.NotEqual(t, "7453e6ac62c0a38ec6f08b5e86adbf3450491be64582ceb9edaf0bbe3213c2d5", fmt.Sprintf("%x", ChannelHashV2(full))) }) t.Run("commits to every field Equals compares", func(t *testing.T) { @@ -56,6 +61,7 @@ func Test_ChannelHashV2(t *testing.T) { "tombstone": func(d *ChannelDefinitionWithID) { d.Tombstone = true }, "source": func(d *ChannelDefinitionWithID) { d.Source = 7 }, "disableNilStreamValues": func(d *ChannelDefinitionWithID) { d.DisableNilStreamValues = true }, + "signingScheme": func(d *ChannelDefinitionWithID) { d.SigningScheme = llotypes.SigningSchemeMerkle }, } { t.Run(name, func(t *testing.T) { mutated := base diff --git a/llo/protocol/conv.go b/llo/protocol/conv.go index 0855918..3ec1def 100644 --- a/llo/protocol/conv.go +++ b/llo/protocol/conv.go @@ -37,6 +37,7 @@ func ChannelDefinitionToProto(d llotypes.ChannelDefinition) *LLOChannelDefinitio Tombstone: d.Tombstone, Source: d.Source, DisableNilStreamValues: d.DisableNilStreamValues, + SigningScheme: string(d.SigningScheme), } } @@ -57,5 +58,6 @@ func ChannelDefinitionFromProto(pb *LLOChannelDefinitionProto) llotypes.ChannelD Tombstone: pb.Tombstone, Source: pb.Source, DisableNilStreamValues: pb.DisableNilStreamValues, + SigningScheme: llotypes.SigningScheme(pb.SigningScheme), } } diff --git a/llo/protocol/generate.go b/llo/protocol/generate.go index a61b933..84b86c6 100644 --- a/llo/protocol/generate.go +++ b/llo/protocol/generate.go @@ -1,6 +1,7 @@ package protocol //go:generate protoc --go_out=. --go_opt=paths=source_relative attested_retirement_report.proto +//go:generate protoc --go_out=. --go_opt=paths=source_relative llo_merkle.proto //go:generate protoc --go_out=. --go_opt=paths=source_relative llo_offchain_config.proto //go:generate protoc --go_out=. --go_opt=paths=source_relative llo_plugin_telemetry.proto //go:generate protoc --go_out=. --go_opt=paths=source_relative plugin_codecs.proto diff --git a/llo/protocol/history_backfill.go b/llo/protocol/history_backfill.go index 6debd30..7fbbb74 100644 --- a/llo/protocol/history_backfill.go +++ b/llo/protocol/history_backfill.go @@ -238,9 +238,10 @@ func TargetChannelTimeResolution(target llotypes.ChannelDefinition) (TimeResolut case llotypes.ReportFormatJSON, llotypes.ReportFormatRetirement, llotypes.ReportFormatCapabilityTrigger, llotypes.ReportFormatEVMStreamlined: return ResolutionSeconds, nil - case llotypes.ReportFormatHistoryBackfill: - // Rejected at admission by ValidateHistoryBackfillTarget. Resolving it - // keeps already committed definitions passing base validation. + case llotypes.ReportFormatHistoryBackfill, llotypes.ReportFormatEVMMerkle: + // Rejected at admission by ValidateHistoryBackfillTarget, and + // ReportFormatEVMMerkle by VerifySigningScheme. Resolving them keeps + // already committed definitions passing base validation. return ResolutionSeconds, nil default: return 0, fmt.Errorf("unsupported history_backfill target report format %s", target.ReportFormat) diff --git a/llo/protocol/llo_merkle.pb.go b/llo/protocol/llo_merkle.pb.go new file mode 100644 index 0000000..a1d60b3 --- /dev/null +++ b/llo/protocol/llo_merkle.pb.go @@ -0,0 +1,294 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc v7.36.2 +// source: llo_merkle.proto + +package protocol + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// LLOMerkleBundleProto is the report a signing family signs once per round. +// Leaves are in ascending channel ID order. The root is not stored: every +// oracle and the keyring recompute it from the leaves. +type LLOMerkleBundleProto struct { + state protoimpl.MessageState `protogen:"open.v1"` + Family uint32 `protobuf:"varint,1,opt,name=family,proto3" json:"family,omitempty"` + Leaves []*LLOMerkleLeafProto `protobuf:"bytes,2,rep,name=leaves,proto3" json:"leaves,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LLOMerkleBundleProto) Reset() { + *x = LLOMerkleBundleProto{} + mi := &file_llo_merkle_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LLOMerkleBundleProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LLOMerkleBundleProto) ProtoMessage() {} + +func (x *LLOMerkleBundleProto) ProtoReflect() protoreflect.Message { + mi := &file_llo_merkle_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LLOMerkleBundleProto.ProtoReflect.Descriptor instead. +func (*LLOMerkleBundleProto) Descriptor() ([]byte, []int) { + return file_llo_merkle_proto_rawDescGZIP(), []int{0} +} + +func (x *LLOMerkleBundleProto) GetFamily() uint32 { + if x != nil { + return x.Family + } + return 0 +} + +func (x *LLOMerkleBundleProto) GetLeaves() []*LLOMerkleLeafProto { + if x != nil { + return x.Leaves + } + return nil +} + +// LLOMerkleLeafProto is one channel report of a bundle. +type LLOMerkleLeafProto struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelID uint32 `protobuf:"varint,1,opt,name=channelID,proto3" json:"channelID,omitempty"` + // reportFormat is the channel's format, one of the family's members. + ReportFormat uint32 `protobuf:"varint,2,opt,name=reportFormat,proto3" json:"reportFormat,omitempty"` + // report is the channel report as its codec encodes it. + Report []byte `protobuf:"bytes,3,opt,name=report,proto3" json:"report,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LLOMerkleLeafProto) Reset() { + *x = LLOMerkleLeafProto{} + mi := &file_llo_merkle_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LLOMerkleLeafProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LLOMerkleLeafProto) ProtoMessage() {} + +func (x *LLOMerkleLeafProto) ProtoReflect() protoreflect.Message { + mi := &file_llo_merkle_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LLOMerkleLeafProto.ProtoReflect.Descriptor instead. +func (*LLOMerkleLeafProto) Descriptor() ([]byte, []int) { + return file_llo_merkle_proto_rawDescGZIP(), []int{1} +} + +func (x *LLOMerkleLeafProto) GetChannelID() uint32 { + if x != nil { + return x.ChannelID + } + return 0 +} + +func (x *LLOMerkleLeafProto) GetReportFormat() uint32 { + if x != nil { + return x.ReportFormat + } + return 0 +} + +func (x *LLOMerkleLeafProto) GetReport() []byte { + if x != nil { + return x.Report + } + return nil +} + +// LLOMerkleDeliveryProto is one leaf of an attested bundle together with the +// proof from the leaf to the bundle root. The root is not stored: the +// verifier recomputes it from the leaf and the proof, and checks the +// signatures over it. +type LLOMerkleDeliveryProto struct { + state protoimpl.MessageState `protogen:"open.v1"` + Family uint32 `protobuf:"varint,1,opt,name=family,proto3" json:"family,omitempty"` + LeafCount uint32 `protobuf:"varint,2,opt,name=leafCount,proto3" json:"leafCount,omitempty"` + LeafIndex uint32 `protobuf:"varint,3,opt,name=leafIndex,proto3" json:"leafIndex,omitempty"` + Leaf *LLOMerkleLeafProto `protobuf:"bytes,4,opt,name=leaf,proto3" json:"leaf,omitempty"` + // proof holds the sibling hashes from the leaf to the root, skipping the + // levels where the node is promoted without a sibling. + Proof [][]byte `protobuf:"bytes,5,rep,name=proof,proto3" json:"proof,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LLOMerkleDeliveryProto) Reset() { + *x = LLOMerkleDeliveryProto{} + mi := &file_llo_merkle_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LLOMerkleDeliveryProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LLOMerkleDeliveryProto) ProtoMessage() {} + +func (x *LLOMerkleDeliveryProto) ProtoReflect() protoreflect.Message { + mi := &file_llo_merkle_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LLOMerkleDeliveryProto.ProtoReflect.Descriptor instead. +func (*LLOMerkleDeliveryProto) Descriptor() ([]byte, []int) { + return file_llo_merkle_proto_rawDescGZIP(), []int{2} +} + +func (x *LLOMerkleDeliveryProto) GetFamily() uint32 { + if x != nil { + return x.Family + } + return 0 +} + +func (x *LLOMerkleDeliveryProto) GetLeafCount() uint32 { + if x != nil { + return x.LeafCount + } + return 0 +} + +func (x *LLOMerkleDeliveryProto) GetLeafIndex() uint32 { + if x != nil { + return x.LeafIndex + } + return 0 +} + +func (x *LLOMerkleDeliveryProto) GetLeaf() *LLOMerkleLeafProto { + if x != nil { + return x.Leaf + } + return nil +} + +func (x *LLOMerkleDeliveryProto) GetProof() [][]byte { + if x != nil { + return x.Proof + } + return nil +} + +var File_llo_merkle_proto protoreflect.FileDescriptor + +const file_llo_merkle_proto_rawDesc = "" + + "\n" + + "\x10llo_merkle.proto\x12\x02v1\"^\n" + + "\x14LLOMerkleBundleProto\x12\x16\n" + + "\x06family\x18\x01 \x01(\rR\x06family\x12.\n" + + "\x06leaves\x18\x02 \x03(\v2\x16.v1.LLOMerkleLeafProtoR\x06leaves\"n\n" + + "\x12LLOMerkleLeafProto\x12\x1c\n" + + "\tchannelID\x18\x01 \x01(\rR\tchannelID\x12\"\n" + + "\freportFormat\x18\x02 \x01(\rR\freportFormat\x12\x16\n" + + "\x06report\x18\x03 \x01(\fR\x06report\"\xae\x01\n" + + "\x16LLOMerkleDeliveryProto\x12\x16\n" + + "\x06family\x18\x01 \x01(\rR\x06family\x12\x1c\n" + + "\tleafCount\x18\x02 \x01(\rR\tleafCount\x12\x1c\n" + + "\tleafIndex\x18\x03 \x01(\rR\tleafIndex\x12*\n" + + "\x04leaf\x18\x04 \x01(\v2\x16.v1.LLOMerkleLeafProtoR\x04leaf\x12\x14\n" + + "\x05proof\x18\x05 \x03(\fR\x05proofB\fZ\n" + + ".;protocolb\x06proto3" + +var ( + file_llo_merkle_proto_rawDescOnce sync.Once + file_llo_merkle_proto_rawDescData []byte +) + +func file_llo_merkle_proto_rawDescGZIP() []byte { + file_llo_merkle_proto_rawDescOnce.Do(func() { + file_llo_merkle_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_llo_merkle_proto_rawDesc), len(file_llo_merkle_proto_rawDesc))) + }) + return file_llo_merkle_proto_rawDescData +} + +var file_llo_merkle_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_llo_merkle_proto_goTypes = []any{ + (*LLOMerkleBundleProto)(nil), // 0: v1.LLOMerkleBundleProto + (*LLOMerkleLeafProto)(nil), // 1: v1.LLOMerkleLeafProto + (*LLOMerkleDeliveryProto)(nil), // 2: v1.LLOMerkleDeliveryProto +} +var file_llo_merkle_proto_depIdxs = []int32{ + 1, // 0: v1.LLOMerkleBundleProto.leaves:type_name -> v1.LLOMerkleLeafProto + 1, // 1: v1.LLOMerkleDeliveryProto.leaf:type_name -> v1.LLOMerkleLeafProto + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_llo_merkle_proto_init() } +func file_llo_merkle_proto_init() { + if File_llo_merkle_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_llo_merkle_proto_rawDesc), len(file_llo_merkle_proto_rawDesc)), + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_llo_merkle_proto_goTypes, + DependencyIndexes: file_llo_merkle_proto_depIdxs, + MessageInfos: file_llo_merkle_proto_msgTypes, + }.Build() + File_llo_merkle_proto = out.File + file_llo_merkle_proto_goTypes = nil + file_llo_merkle_proto_depIdxs = nil +} diff --git a/llo/protocol/llo_merkle.proto b/llo/protocol/llo_merkle.proto new file mode 100644 index 0000000..0f12733 --- /dev/null +++ b/llo/protocol/llo_merkle.proto @@ -0,0 +1,41 @@ +syntax="proto3"; + +package v1; +option go_package = ".;protocol"; + +// WARNING +// Use extreme caution making changes in this file +// All changes MUST be backwards compatible +// Every oracle must build byte identical bundles, and deliveries are persisted +// and verified by the Data Streams server and onchain. + +// LLOMerkleBundleProto is the report a signing family signs once per round. +// Leaves are in ascending channel ID order. The root is not stored: every +// oracle and the keyring recompute it from the leaves. +message LLOMerkleBundleProto { + uint32 family = 1; + repeated LLOMerkleLeafProto leaves = 2; +} + +// LLOMerkleLeafProto is one channel report of a bundle. +message LLOMerkleLeafProto { + uint32 channelID = 1; + // reportFormat is the channel's format, one of the family's members. + uint32 reportFormat = 2; + // report is the channel report as its codec encodes it. + bytes report = 3; +} + +// LLOMerkleDeliveryProto is one leaf of an attested bundle together with the +// proof from the leaf to the bundle root. The root is not stored: the +// verifier recomputes it from the leaf and the proof, and checks the +// signatures over it. +message LLOMerkleDeliveryProto { + uint32 family = 1; + uint32 leafCount = 2; + uint32 leafIndex = 3; + LLOMerkleLeafProto leaf = 4; + // proof holds the sibling hashes from the leaf to the root, skipping the + // levels where the node is promoted without a sibling. + repeated bytes proof = 5; +} diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go new file mode 100644 index 0000000..c0db22c --- /dev/null +++ b/llo/protocol/merkle.go @@ -0,0 +1,343 @@ +package protocol + +import ( + "encoding/binary" + "errors" + "fmt" + + "github.com/ethereum/go-ethereum/crypto" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + ocr2types "github.com/smartcontractkit/libocr/offchainreporting2plus/types" +) + +// Merkle batched report signing. +// +// Channels with SigningSchemeMerkle are not signed one report at a time. +// Reports groups them by signing family into bundle reports, the keyring signs +// the Merkle root of each bundle once, and the transmitter expands an attested +// bundle into one delivery per leaf, carrying the proof from the leaf to the +// root. The verifier recomputes the root from the delivery and checks the +// signatures over it. +// +// The tree is domain separated as in RFC 6962. A leaf hashes as +// H(0x00 ‖ family ‖ reportFormat ‖ channelID ‖ H(report)) and a node as +// H(0x01 ‖ left ‖ right). An odd node is promoted unchanged to the next level, +// never duplicated, and the leaf count is part of the signed message, so two +// different leaf sets cannot share a signed root. Integers are big endian: +// uint32 for the family, format, channel ID and leaf count, uint64 for seqNr. +// H is keccak256 for the EVM family, the only family so far. + +const ( + merkleLeafPrefix byte = 0x00 + merkleNodePrefix byte = 0x01 + + // MerkleSigningDomain prefixes the message a bundle root is signed under. + MerkleSigningDomain = "LLO_MERKLE_V1" + + // MaxMerkleBundleLeaves bounds the leaves of one bundle. A bundle holds at + // most one report per channel definition. + MaxMerkleBundleLeaves = MaxOutcomeChannelDefinitionsLength +) + +// MerkleHash is a node of the tree. +type MerkleHash = [32]byte + +// MerkleFamily returns the signing family that channels in format join under +// SigningSchemeMerkle, and false if format has none. +// +// The EVM family covers every format with a codec in llo/reportcodec/evm. They +// all produce reports for EVM verifiers and hash with keccak256, so one bundle +// can hold all of them. +func MerkleFamily(format llotypes.ReportFormat) (llotypes.ReportFormat, bool) { + switch format { + case llotypes.ReportFormatEVMPremiumLegacy, + llotypes.ReportFormatEVMABIEncodeUnpacked, + llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined: + return llotypes.ReportFormatEVMMerkle, true + default: + return 0, false + } +} + +// IsMerkleFamily reports whether format is a signing family. +func IsMerkleFamily(format llotypes.ReportFormat) bool { + return format == llotypes.ReportFormatEVMMerkle +} + +// VerifySigningScheme checks how a channel definition is signed. A signing +// family is never a channel format, the scheme must be empty or +// SigningSchemeMerkle, and SigningSchemeMerkle needs a format with a signing +// family. +func VerifySigningScheme(cd llotypes.ChannelDefinition) error { + if IsMerkleFamily(cd.ReportFormat) { + return fmt.Errorf("report format %s is a signing family, not a channel format", cd.ReportFormat) + } + switch cd.SigningScheme { + case llotypes.SigningSchemeDefault: + return nil + case llotypes.SigningSchemeMerkle: + if _, ok := MerkleFamily(cd.ReportFormat); !ok { + return fmt.Errorf("signing scheme %q is not supported for report format %s", cd.SigningScheme, cd.ReportFormat) + } + return nil + default: + return fmt.Errorf("unknown signing scheme %q", cd.SigningScheme) + } +} + +func keccak(parts ...[]byte) (h MerkleHash) { + copy(h[:], crypto.Keccak256(parts...)) + return h +} + +func be32(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) } + +// MerkleLeafHash returns the leaf hash of leaf in a bundle of family. +func MerkleLeafHash(family llotypes.ReportFormat, leaf *LLOMerkleLeafProto) MerkleHash { + reportHash := keccak(leaf.Report) + return keccak([]byte{merkleLeafPrefix}, be32(uint32(family)), be32(leaf.ReportFormat), be32(leaf.ChannelID), reportHash[:]) +} + +func merkleNodeHash(left, right MerkleHash) MerkleHash { + return keccak([]byte{merkleNodePrefix}, left[:], right[:]) +} + +// MerkleSigningMessage returns the message the keyring signs for a bundle. +// The config digest and seqNr play the role of the report context, so a root +// cannot be replayed into another round or another configuration. +func MerkleSigningMessage(digest ocr2types.ConfigDigest, seqNr uint64, family llotypes.ReportFormat, leafCount uint32, root MerkleHash) MerkleHash { + return keccak([]byte(MerkleSigningDomain), digest[:], binary.BigEndian.AppendUint64(nil, seqNr), be32(uint32(family)), be32(leafCount), root[:]) +} + +// merkleTree holds every level of a tree, leaves first and the root last. +type merkleTree [][]MerkleHash + +func newMerkleTree(leaves []MerkleHash) (merkleTree, error) { + if len(leaves) == 0 { + return nil, errors.New("merkle tree needs at least one leaf") + } + tree := merkleTree{leaves} + for level := leaves; len(level) > 1; { + next := make([]MerkleHash, 0, (len(level)+1)/2) + for i := 0; i+1 < len(level); i += 2 { + next = append(next, merkleNodeHash(level[i], level[i+1])) + } + if len(level)%2 == 1 { + next = append(next, level[len(level)-1]) + } + tree = append(tree, next) + level = next + } + return tree, nil +} + +func (t merkleTree) root() MerkleHash { return t[len(t)-1][0] } + +// proof returns the sibling hashes from leaf index to the root. A level where +// the node is promoted contributes none. +func (t merkleTree) proof(index int) [][]byte { + var proof [][]byte + for _, level := range t[:len(t)-1] { + if sibling := index ^ 1; sibling < len(level) { + proof = append(proof, level[sibling][:]) + } + index /= 2 + } + return proof +} + +// MerkleRoot returns the root over leaves. +func MerkleRoot(leaves []MerkleHash) (MerkleHash, error) { + tree, err := newMerkleTree(leaves) + if err != nil { + return MerkleHash{}, err + } + return tree.root(), nil +} + +// MerkleRootFromProof returns the root that leaf at index of a tree with +// leafCount leaves hashes up to with proof. It fails when the proof has the +// wrong length for the position, so a valid proof cannot be padded. +func MerkleRootFromProof(leaf MerkleHash, index, leafCount uint32, proof [][]byte) (MerkleHash, error) { + if leafCount == 0 || index >= leafCount { + return MerkleHash{}, fmt.Errorf("leaf index %d out of range for %d leaves", index, leafCount) + } + h := leaf + for n := leafCount; n > 1; n = (n + 1) / 2 { + if index^1 < n { + if len(proof) == 0 { + return MerkleHash{}, errors.New("merkle proof too short") + } + if len(proof[0]) != len(MerkleHash{}) { + return MerkleHash{}, fmt.Errorf("merkle proof hash has %d bytes, expected %d", len(proof[0]), len(MerkleHash{})) + } + sibling := MerkleHash(proof[0]) + proof = proof[1:] + if index%2 == 0 { + h = merkleNodeHash(h, sibling) + } else { + h = merkleNodeHash(sibling, h) + } + } + index /= 2 + } + if len(proof) != 0 { + return MerkleHash{}, errors.New("merkle proof too long") + } + return h, nil +} + +// EncodeMerkleBundle encodes a bundle deterministically, so every oracle +// produces the same bytes from the same leaves. +func EncodeMerkleBundle(bundle *LLOMerkleBundleProto) ([]byte, error) { + return deterministicMarshal.Marshal(bundle) +} + +// DecodeMerkleBundle decodes and checks a bundle: a known family, between one +// and MaxMerkleBundleLeaves leaves, and every leaf in a member format of the +// family. +func DecodeMerkleBundle(b []byte) (*LLOMerkleBundleProto, error) { + bundle := new(LLOMerkleBundleProto) + if err := proto.Unmarshal(b, bundle); err != nil { + return nil, fmt.Errorf("failed to decode merkle bundle: %w", err) + } + family := llotypes.ReportFormat(bundle.Family) + if !IsMerkleFamily(family) { + return nil, fmt.Errorf("merkle bundle has unknown family %s", family) + } + if len(bundle.Leaves) == 0 || len(bundle.Leaves) > MaxMerkleBundleLeaves { + return nil, fmt.Errorf("merkle bundle has %d leaves, expected between 1 and %d", len(bundle.Leaves), MaxMerkleBundleLeaves) + } + for i, leaf := range bundle.Leaves { + if err := verifyMerkleLeaf(family, leaf); err != nil { + return nil, fmt.Errorf("merkle bundle leaf %d: %w", i, err) + } + } + return bundle, nil +} + +func verifyMerkleLeaf(family llotypes.ReportFormat, leaf *LLOMerkleLeafProto) error { + if leaf == nil { + return errors.New("nil leaf") + } + if f, ok := MerkleFamily(llotypes.ReportFormat(leaf.ReportFormat)); !ok || f != family { + return fmt.Errorf("report format %s is not a member of family %s", llotypes.ReportFormat(leaf.ReportFormat), family) + } + return nil +} + +func bundleTree(bundle *LLOMerkleBundleProto) (merkleTree, error) { + family := llotypes.ReportFormat(bundle.Family) + leaves := make([]MerkleHash, len(bundle.Leaves)) + for i, leaf := range bundle.Leaves { + leaves[i] = MerkleLeafHash(family, leaf) + } + return newMerkleTree(leaves) +} + +// MerkleBundleRoot returns the root of a decoded bundle. +func MerkleBundleRoot(bundle *LLOMerkleBundleProto) (MerkleHash, error) { + tree, err := bundleTree(bundle) + if err != nil { + return MerkleHash{}, err + } + return tree.root(), nil +} + +// ExpandMerkleBundle returns one delivery per leaf of a decoded bundle, in +// leaf order, each with its proof to the bundle root. +func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleDeliveryProto, error) { + tree, err := bundleTree(bundle) + if err != nil { + return nil, err + } + leafCount := uint32(len(bundle.Leaves)) //nolint:gosec // bounded by MaxMerkleBundleLeaves on decode + deliveries := make([]*LLOMerkleDeliveryProto, len(bundle.Leaves)) + for i, leaf := range bundle.Leaves { + deliveries[i] = &LLOMerkleDeliveryProto{ + Family: bundle.Family, + LeafCount: leafCount, + LeafIndex: uint32(i), //nolint:gosec // below leafCount + Leaf: leaf, + Proof: tree.proof(i), + } + } + return deliveries, nil +} + +// EncodeMerkleDelivery encodes a delivery deterministically. +func EncodeMerkleDelivery(delivery *LLOMerkleDeliveryProto) ([]byte, error) { + return deterministicMarshal.Marshal(delivery) +} + +// DecodeMerkleDelivery decodes a delivery and returns the root its leaf and +// proof hash up to. The caller checks the signatures over +// MerkleSigningMessage with that root. +func DecodeMerkleDelivery(b []byte) (*LLOMerkleDeliveryProto, MerkleHash, error) { + delivery := new(LLOMerkleDeliveryProto) + if err := proto.Unmarshal(b, delivery); err != nil { + return nil, MerkleHash{}, fmt.Errorf("failed to decode merkle delivery: %w", err) + } + family := llotypes.ReportFormat(delivery.Family) + if !IsMerkleFamily(family) { + return nil, MerkleHash{}, fmt.Errorf("merkle delivery has unknown family %s", family) + } + if delivery.LeafCount > MaxMerkleBundleLeaves { + return nil, MerkleHash{}, fmt.Errorf("merkle delivery has %d leaves, max %d", delivery.LeafCount, MaxMerkleBundleLeaves) + } + if err := verifyMerkleLeaf(family, delivery.Leaf); err != nil { + return nil, MerkleHash{}, fmt.Errorf("merkle delivery: %w", err) + } + root, err := MerkleRootFromProof(MerkleLeafHash(family, delivery.Leaf), delivery.LeafIndex, delivery.LeafCount, delivery.Proof) + if err != nil { + return nil, MerkleHash{}, fmt.Errorf("merkle delivery: %w", err) + } + return delivery, root, nil +} + +// SplitMerkleBundle encodes leaves, in order, into as few consecutive bundles +// of family as keep each encoded bundle within maxBytes. A leaf that does not +// fit in a bundle on its own is left out and its index returned in oversized. +func SplitMerkleBundle(family llotypes.ReportFormat, leaves []*LLOMerkleLeafProto, maxBytes int) (bundles [][]byte, oversized []int, err error) { + familyField := 0 + if family != 0 { + familyField = protowire.SizeTag(1) + protowire.SizeVarint(uint64(family)) + } + var current []*LLOMerkleLeafProto + size := familyField + flush := func() error { + if len(current) == 0 { + return nil + } + b, err := EncodeMerkleBundle(&LLOMerkleBundleProto{Family: uint32(family), Leaves: current}) + if err != nil { + return err + } + bundles = append(bundles, b) + current = nil + size = familyField + return nil + } + for i, leaf := range leaves { + leafSize := protowire.SizeTag(2) + protowire.SizeBytes(proto.Size(leaf)) + if familyField+leafSize > maxBytes { + oversized = append(oversized, i) + continue + } + if size+leafSize > maxBytes || len(current) == MaxMerkleBundleLeaves { + if err := flush(); err != nil { + return nil, nil, err + } + } + current = append(current, leaf) + size += leafSize + } + if err := flush(); err != nil { + return nil, nil, err + } + return bundles, oversized, nil +} diff --git a/llo/protocol/merkle_test.go b/llo/protocol/merkle_test.go new file mode 100644 index 0000000..4648ca7 --- /dev/null +++ b/llo/protocol/merkle_test.go @@ -0,0 +1,427 @@ +package protocol + +import ( + "encoding/hex" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + ocr2types "github.com/smartcontractkit/libocr/offchainreporting2plus/types" +) + +const evmMerkle = llotypes.ReportFormatEVMMerkle + +func testLeaves(n int) []*LLOMerkleLeafProto { + formats := []llotypes.ReportFormat{ + llotypes.ReportFormatEVMPremiumLegacy, + llotypes.ReportFormatEVMABIEncodeUnpacked, + llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined, + } + leaves := make([]*LLOMerkleLeafProto, n) + for i := range leaves { + leaves[i] = &LLOMerkleLeafProto{ + ChannelID: uint32(i + 1), //nolint:gosec // test + ReportFormat: uint32(formats[i%len(formats)]), + Report: []byte(fmt.Sprintf("report %d", i)), + } + } + return leaves +} + +func leafHashes(leaves []*LLOMerkleLeafProto) []MerkleHash { + hashes := make([]MerkleHash, len(leaves)) + for i, leaf := range leaves { + hashes[i] = MerkleLeafHash(evmMerkle, leaf) + } + return hashes +} + +func Test_MerkleFamily(t *testing.T) { + for _, rf := range []llotypes.ReportFormat{ + llotypes.ReportFormatEVMPremiumLegacy, + llotypes.ReportFormatEVMABIEncodeUnpacked, + llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined, + } { + family, ok := MerkleFamily(rf) + assert.True(t, ok, rf.String()) + assert.Equal(t, evmMerkle, family, rf.String()) + } + for _, rf := range []llotypes.ReportFormat{ + llotypes.ReportFormatJSON, + llotypes.ReportFormatRetirement, + llotypes.ReportFormatCapabilityTrigger, + llotypes.ReportFormatHistoryBackfill, + llotypes.ReportFormatEVMMerkle, + } { + _, ok := MerkleFamily(rf) + assert.False(t, ok, rf.String()) + } +} + +func Test_VerifySigningScheme(t *testing.T) { + require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON})) + require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: llotypes.SigningSchemeMerkle})) + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON, SigningScheme: llotypes.SigningSchemeMerkle}), + `signing scheme "merkle" is not supported for report format json`) + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMMerkle}), + `report format evm_merkle is a signing family, not a channel format`) + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: "both"}), + `unknown signing scheme "both"`) +} + +func Test_MerkleRoot_Shape(t *testing.T) { + l := leafHashes(testLeaves(5)) + node := merkleNodeHash + + cases := []struct { + n int + want MerkleHash + }{ + {1, l[0]}, + {2, node(l[0], l[1])}, + // The odd leaf is promoted, not paired with a copy of itself. + {3, node(node(l[0], l[1]), l[2])}, + {4, node(node(l[0], l[1]), node(l[2], l[3]))}, + {5, node(node(node(l[0], l[1]), node(l[2], l[3])), l[4])}, + } + for _, c := range cases { + root, err := MerkleRoot(l[:c.n]) + require.NoError(t, err) + assert.Equal(t, c.want, root, "n=%d", c.n) + } + + _, err := MerkleRoot(nil) + require.Error(t, err) +} + +func Test_MerkleLeafHash_DomainSeparation(t *testing.T) { + leaf := testLeaves(1)[0] + h := MerkleLeafHash(evmMerkle, leaf) + + other := proto.Clone(leaf).(*LLOMerkleLeafProto) + other.ChannelID++ + assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "channel ID") + + other = proto.Clone(leaf).(*LLOMerkleLeafProto) + other.ReportFormat = uint32(llotypes.ReportFormatEVMStreamlined) + assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "report format") + + assert.NotEqual(t, h, MerkleLeafHash(evmMerkle+1, leaf), "family") + + // A leaf hash never equals a node hash over the same bytes. + assert.NotEqual(t, keccak([]byte{merkleNodePrefix}, h[:], h[:]), MerkleLeafHash(evmMerkle, leaf)) +} + +func Test_MerkleProof_EveryLeaf(t *testing.T) { + for n := 1; n <= 33; n++ { + hashes := leafHashes(testLeaves(n)) + tree, err := newMerkleTree(hashes) + require.NoError(t, err) + root := tree.root() + count := uint32(n) //nolint:gosec // test + + for i := range n { + index := uint32(i) //nolint:gosec // test + proof := tree.proof(i) + + got, err := MerkleRootFromProof(hashes[i], index, count, proof) + require.NoError(t, err, "n=%d i=%d", n, i) + require.Equal(t, root, got, "n=%d i=%d", n, i) + + // A different leaf does not reach the root. + other := hashes[(i+1)%n] + if other != hashes[i] { + got, err = MerkleRootFromProof(other, index, count, proof) + if err == nil { + assert.NotEqual(t, root, got, "changed leaf n=%d i=%d", n, i) + } + } + // Neither does the same leaf at another index or in a tree of + // another size. + if n > 1 { + got, err = MerkleRootFromProof(hashes[i], (index+1)%count, count, proof) + if err == nil { + assert.NotEqual(t, root, got, "changed index n=%d i=%d", n, i) + } + } + // A proof can reach the same root under another leaf count, which + // is why the count is part of the signed message. + got, err = MerkleRootFromProof(hashes[i], index, count+1, proof) + if err == nil { + signed := MerkleSigningMessage(ocr2types.ConfigDigest{}, 1, evmMerkle, count, root) + assert.NotEqual(t, signed, MerkleSigningMessage(ocr2types.ConfigDigest{}, 1, evmMerkle, count+1, got), "changed leaf count n=%d i=%d", n, i) + } + // A padded or truncated proof is rejected. + _, err = MerkleRootFromProof(hashes[i], index, count, append(proof, root[:])) + require.Error(t, err) + if len(proof) > 0 { + _, err = MerkleRootFromProof(hashes[i], index, count, proof[:len(proof)-1]) + require.Error(t, err) + } + } + } +} + +func Test_MerkleRootFromProof_Errors(t *testing.T) { + leaf := MerkleHash{1} + _, err := MerkleRootFromProof(leaf, 0, 0, nil) + require.Error(t, err) + _, err = MerkleRootFromProof(leaf, 2, 2, nil) + require.Error(t, err) + _, err = MerkleRootFromProof(leaf, 0, 2, [][]byte{{1, 2, 3}}) + require.EqualError(t, err, "merkle proof hash has 3 bytes, expected 32") +} + +// The golden vectors are the shared reference for the verifier contract and +// the Data Streams server. Changing them breaks every delivery verifier. They +// were checked against an independent keccak256 implementation of the scheme +// described in merkle.go. +func Test_Merkle_GoldenVectors(t *testing.T) { + bundle := &LLOMerkleBundleProto{ + Family: uint32(evmMerkle), + Leaves: []*LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, + {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, + {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, + }, + } + digest := ocr2types.ConfigDigest{0x00, 0x09, 0xaa} + seqNr := uint64(42) + + leaf0 := MerkleLeafHash(evmMerkle, bundle.Leaves[0]) + assert.Equal(t, "c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", hex.EncodeToString(leaf0[:])) + + root, err := MerkleBundleRoot(bundle) + require.NoError(t, err) + assert.Equal(t, "cee789eea2b2295270c2507936405a5dc9e3af1fcfc3c8c9cb605bae8e57b4e9", hex.EncodeToString(root[:])) + + msg := MerkleSigningMessage(digest, seqNr, evmMerkle, uint32(len(bundle.Leaves)), root) + assert.Equal(t, "82a749ca4b50caa0ea66a307bb3cffbc933bca6be71832179c775be8dee4ebac", hex.EncodeToString(msg[:])) + + deliveries, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + proofs := make([][]string, len(deliveries)) + for i, d := range deliveries { + for _, p := range d.Proof { + proofs[i] = append(proofs[i], hex.EncodeToString(p)) + } + } + assert.Equal(t, [][]string{ + {"a9ca2f12f60482dba94c617c2c752d6f1770af1e796a3fe319e3a69bba71fc5a", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"ae0b62b9ce280ffba7c5c0c1cad41c77928a9a408988e550d857e6ffe04dad22", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"4d1c23853ce24ad78df071013d6300555c3d36fa656a046b94c750b74661660a", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + // The last leaf is promoted twice, so its only sibling is the root of + // the first four. + {"7e4ba02ae94d30d32ef66b329b325986ebadd188a13178fb2c0b9159268b9369"}, + }, proofs) +} + +func Test_MerkleBundle_Codec(t *testing.T) { + t.Run("round trip", func(t *testing.T) { + bundle := &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(4)} + b, err := EncodeMerkleBundle(bundle) + require.NoError(t, err) + decoded, err := DecodeMerkleBundle(b) + require.NoError(t, err) + assert.True(t, proto.Equal(bundle, decoded)) + }) + + encode := func(bundle *LLOMerkleBundleProto) []byte { + b, err := EncodeMerkleBundle(bundle) + require.NoError(t, err) + return b + } + cases := []struct { + name string + bundle *LLOMerkleBundleProto + err string + }{ + {"unknown family", &LLOMerkleBundleProto{Family: uint32(llotypes.ReportFormatJSON), Leaves: testLeaves(1)}, "merkle bundle has unknown family json"}, + {"no leaves", &LLOMerkleBundleProto{Family: uint32(evmMerkle)}, "merkle bundle has 0 leaves, expected between 1 and 2000"}, + {"non member leaf", &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: []*LLOMerkleLeafProto{{ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatJSON)}}}, "merkle bundle leaf 0: report format json is not a member of family evm_merkle"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := DecodeMerkleBundle(encode(c.bundle)) + require.EqualError(t, err, c.err) + }) + } + + t.Run("too many leaves", func(t *testing.T) { + _, err := DecodeMerkleBundle(encode(&LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(MaxMerkleBundleLeaves + 1)})) + require.EqualError(t, err, "merkle bundle has 2001 leaves, expected between 1 and 2000") + }) + + t.Run("garbage", func(t *testing.T) { + _, err := DecodeMerkleBundle([]byte{0xff, 0xff}) + require.Error(t, err) + }) +} + +func Test_MerkleDelivery(t *testing.T) { + bundle := &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(7)} + root, err := MerkleBundleRoot(bundle) + require.NoError(t, err) + + deliveries, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + require.Len(t, deliveries, 7) + + for i, d := range deliveries { + assert.Equal(t, uint32(i), d.LeafIndex) //nolint:gosec // test + assert.Equal(t, uint32(7), d.LeafCount) + assert.True(t, proto.Equal(bundle.Leaves[i], d.Leaf)) + + b, err := EncodeMerkleDelivery(d) + require.NoError(t, err) + decoded, got, err := DecodeMerkleDelivery(b) + require.NoError(t, err) + assert.Equal(t, root, got) + assert.True(t, proto.Equal(d, decoded)) + } + + tamper := func(f func(d *LLOMerkleDeliveryProto)) (MerkleHash, error) { + d := proto.Clone(deliveries[3]).(*LLOMerkleDeliveryProto) + f(d) + b, err := EncodeMerkleDelivery(d) + require.NoError(t, err) + _, got, err := DecodeMerkleDelivery(b) + return got, err + } + for name, f := range map[string]func(d *LLOMerkleDeliveryProto){ + "report": func(d *LLOMerkleDeliveryProto) { d.Leaf.Report = append(d.Leaf.Report, 0) }, + "channel": func(d *LLOMerkleDeliveryProto) { d.Leaf.ChannelID++ }, + "format": func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMPremiumLegacy) }, + "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, + "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, + // A changed leaf count can still reach the root. The signed message + // binds it, see Test_MerkleProof_EveryLeaf. + "leaf count": func(d *LLOMerkleDeliveryProto) { d.LeafCount = 9 }, + } { + got, err := tamper(f) + if err == nil { + assert.NotEqual(t, root, got, name) + } + } + + for name, c := range map[string]struct { + f func(d *LLOMerkleDeliveryProto) + err string + }{ + "family": {func(d *LLOMerkleDeliveryProto) { d.Family = uint32(llotypes.ReportFormatJSON) }, "merkle delivery has unknown family json"}, + "non member": {func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatJSON) }, "merkle delivery: report format json is not a member of family evm_merkle"}, + "no leaf": {func(d *LLOMerkleDeliveryProto) { d.Leaf = nil }, "merkle delivery: nil leaf"}, + "index range": {func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 7 }, "merkle delivery: leaf index 7 out of range for 7 leaves"}, + } { + _, err := tamper(c.f) + require.EqualError(t, err, c.err, name) + } +} + +func Test_SplitMerkleBundle(t *testing.T) { + leaves := testLeaves(50) + leafSize := len(mustEncodeBundle(t, &LLOMerkleBundleProto{Leaves: leaves[:1]})) + familySize := len(mustEncodeBundle(t, &LLOMerkleBundleProto{Family: uint32(evmMerkle)})) + + t.Run("fits in one bundle", func(t *testing.T) { + bundles, oversized, err := SplitMerkleBundle(evmMerkle, leaves, 1<<20) + require.NoError(t, err) + assert.Empty(t, oversized) + require.Len(t, bundles, 1) + assert.Equal(t, mustEncodeBundle(t, &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: leaves}), bundles[0]) + }) + + t.Run("splits by size, in order", func(t *testing.T) { + maxBytes := familySize + 7*leafSize + bundles, oversized, err := SplitMerkleBundle(evmMerkle, leaves, maxBytes) + require.NoError(t, err) + assert.Empty(t, oversized) + require.Greater(t, len(bundles), 1) + + var all []*LLOMerkleLeafProto + for i, b := range bundles { + assert.LessOrEqual(t, len(b), maxBytes) + decoded, err := DecodeMerkleBundle(b) + require.NoError(t, err) + all = append(all, decoded.Leaves...) + if i < len(bundles)-1 { + next := leaves[len(all)] + withNext := mustEncodeBundle(t, &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: append(decoded.Leaves, next)}) + assert.Greater(t, len(withNext), maxBytes, "bundle %d is not full", i) + } + } + require.Len(t, all, len(leaves)) + for i := range leaves { + assert.True(t, proto.Equal(leaves[i], all[i])) + } + }) + + t.Run("oversized leaf is left out", func(t *testing.T) { + big := &LLOMerkleLeafProto{ChannelID: 99, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: make([]byte, 200)} + input := []*LLOMerkleLeafProto{leaves[0], big, leaves[1]} + bundles, oversized, err := SplitMerkleBundle(evmMerkle, input, 100) + require.NoError(t, err) + assert.Equal(t, []int{1}, oversized) + require.Len(t, bundles, 1) + decoded, err := DecodeMerkleBundle(bundles[0]) + require.NoError(t, err) + require.Len(t, decoded.Leaves, 2) + }) + + t.Run("no leaves", func(t *testing.T) { + bundles, oversized, err := SplitMerkleBundle(evmMerkle, nil, 100) + require.NoError(t, err) + assert.Empty(t, bundles) + assert.Empty(t, oversized) + }) +} + +func mustEncodeBundle(t *testing.T, bundle *LLOMerkleBundleProto) []byte { + t.Helper() + b, err := EncodeMerkleBundle(bundle) + require.NoError(t, err) + return b +} + +func FuzzMerkleDelivery(f *testing.F) { + f.Add(uint16(1), uint16(0), []byte("a"), uint16(0)) + f.Add(uint16(7), uint16(6), []byte("seven"), uint16(3)) + f.Add(uint16(64), uint16(31), []byte{}, uint16(100)) + f.Fuzz(func(t *testing.T, n, index uint16, report []byte, flip uint16) { + count := int(n%200) + 1 + i := int(index) % count + leaves := testLeaves(count) + leaves[i].Report = report + bundle := &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: leaves} + + root, err := MerkleBundleRoot(bundle) + require.NoError(t, err) + deliveries, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + b, err := EncodeMerkleDelivery(deliveries[i]) + require.NoError(t, err) + _, got, err := DecodeMerkleDelivery(b) + require.NoError(t, err) + require.Equal(t, root, got) + + // Flipping any bit of the delivery either fails to decode or no + // longer reaches the root. The one exception is the leaf count, which + // the root does not bind but the signed message does. + bit := int(flip) % (len(b) * 8) + tampered := append([]byte(nil), b...) + tampered[bit/8] ^= 1 << (bit % 8) + d, got, err := DecodeMerkleDelivery(tampered) + if err == nil && got == root && d.LeafCount == deliveries[i].LeafCount { + require.True(t, proto.Equal(deliveries[i], d), "a changed delivery reached the root") + } + }) +} diff --git a/llo/protocol/plugin_codecs.pb.go b/llo/protocol/plugin_codecs.pb.go index 42b88d2..fd8400c 100644 --- a/llo/protocol/plugin_codecs.pb.go +++ b/llo/protocol/plugin_codecs.pb.go @@ -590,8 +590,12 @@ type LLOChannelDefinitionProto struct { Tombstone bool `protobuf:"varint,4,opt,name=tombstone,proto3" json:"tombstone,omitempty"` Source uint32 `protobuf:"varint,5,opt,name=source,proto3" json:"source,omitempty"` DisableNilStreamValues bool `protobuf:"varint,6,opt,name=disableNilStreamValues,proto3" json:"disableNilStreamValues,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // signingScheme selects how the channel's reports are signed. Empty signs + // every report on its own. It is omitted from the wire when empty, so the + // encoding and channel hash of every definition without it are unchanged. + SigningScheme string `protobuf:"bytes,7,opt,name=signingScheme,proto3" json:"signingScheme,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *LLOChannelDefinitionProto) Reset() { @@ -666,6 +670,13 @@ func (x *LLOChannelDefinitionProto) GetDisableNilStreamValues() bool { return false } +func (x *LLOChannelDefinitionProto) GetSigningScheme() string { + if x != nil { + return x.SigningScheme + } + return "" +} + type LLOStreamDefinition struct { state protoimpl.MessageState `protogen:"open.v1"` StreamID uint32 `protobuf:"varint,1,opt,name=streamID,proto3" json:"streamID,omitempty"` @@ -1601,14 +1612,15 @@ const file_plugin_codecs_proto_rawDesc = "" + "\rfirstSequence\x18\x02 \x01(\x04R\rfirstSequence\x12\x16\n" + "\x06counts\x18\x03 \x03(\rR\x06counts\x12\\\n" + ")chunkFirstObservationTimestampNanoseconds\x18\x04 \x03(\x04R)chunkFirstObservationTimestampNanoseconds\x12P\n" + - "#lastObservationTimestampNanoseconds\x18\x05 \x01(\x04R#lastObservationTimestampNanoseconds\"\xf4\x01\n" + + "#lastObservationTimestampNanoseconds\x18\x05 \x01(\x04R#lastObservationTimestampNanoseconds\"\x9a\x02\n" + "\x19LLOChannelDefinitionProto\x12\"\n" + "\freportFormat\x18\x01 \x01(\rR\freportFormat\x121\n" + "\astreams\x18\x02 \x03(\v2\x17.v1.LLOStreamDefinitionR\astreams\x12\x12\n" + "\x04opts\x18\x03 \x01(\fR\x04opts\x12\x1c\n" + "\ttombstone\x18\x04 \x01(\bR\ttombstone\x12\x16\n" + "\x06source\x18\x05 \x01(\rR\x06source\x126\n" + - "\x16disableNilStreamValues\x18\x06 \x01(\bR\x16disableNilStreamValues\"Q\n" + + "\x16disableNilStreamValues\x18\x06 \x01(\bR\x16disableNilStreamValues\x12$\n" + + "\rsigningScheme\x18\a \x01(\tR\rsigningScheme\"Q\n" + "\x13LLOStreamDefinition\x12\x1a\n" + "\bstreamID\x18\x01 \x01(\rR\bstreamID\x12\x1e\n" + "\n" + diff --git a/llo/protocol/plugin_codecs.proto b/llo/protocol/plugin_codecs.proto index 1e26abf..c1b33b9 100644 --- a/llo/protocol/plugin_codecs.proto +++ b/llo/protocol/plugin_codecs.proto @@ -122,6 +122,10 @@ message LLOChannelDefinitionProto { bool tombstone = 4; uint32 source = 5; bool disableNilStreamValues = 6; + // signingScheme selects how the channel's reports are signed. Empty signs + // every report on its own. It is omitted from the wire when empty, so the + // encoding and channel hash of every definition without it are unchanged. + string signingScheme = 7; } message LLOStreamDefinition { diff --git a/llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 b/llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 new file mode 100644 index 0000000..8e7150f --- /dev/null +++ b/llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 @@ -0,0 +1,5 @@ +go test fuzz v1 +uint16(81) +uint16(92) +[]byte("0") +uint16(28) diff --git a/llo/protocol/time_resolution.go b/llo/protocol/time_resolution.go index 78f9372..96cc3d5 100644 --- a/llo/protocol/time_resolution.go +++ b/llo/protocol/time_resolution.go @@ -38,7 +38,7 @@ func ReportTimeResolution(optsCache *OptsCache, cd llotypes.ChannelDefinition, c return ResolutionNanoseconds, nil case llotypes.ReportFormatHistoryBackfill: return 0, fmt.Errorf("report format %s is encoded with the target channel's codec", cd.ReportFormat) - case llotypes.ReportFormatRetirement, llotypes.ReportFormatCapabilityTrigger: + case llotypes.ReportFormatRetirement, llotypes.ReportFormatCapabilityTrigger, llotypes.ReportFormatEVMMerkle: return 0, fmt.Errorf("report format %s has no report codec", cd.ReportFormat) default: return 0, fmt.Errorf("report format %s has no time resolution mapping", cd.ReportFormat) diff --git a/llo/protocol/time_resolution_test.go b/llo/protocol/time_resolution_test.go index cb1884d..a745d24 100644 --- a/llo/protocol/time_resolution_test.go +++ b/llo/protocol/time_resolution_test.go @@ -26,6 +26,7 @@ func Test_ReportTimeResolution_ClassifiesEveryReportFormat(t *testing.T) { llotypes.ReportFormatHistoryBackfill: {err: "encoded with the target channel's codec"}, llotypes.ReportFormatRetirement: {err: "has no report codec"}, llotypes.ReportFormatCapabilityTrigger: {err: "has no report codec"}, + llotypes.ReportFormatEVMMerkle: {err: "has no report codec"}, } for _, rf := range llotypes.ReportFormats { t.Run(rf.String(), func(t *testing.T) { diff --git a/llo/reportcodec/evm/report_codec_evm_merkle.go b/llo/reportcodec/evm/report_codec_evm_merkle.go new file mode 100644 index 0000000..acd790c --- /dev/null +++ b/llo/reportcodec/evm/report_codec_evm_merkle.go @@ -0,0 +1,99 @@ +package evm + +import ( + "encoding/binary" + "fmt" + "slices" + + "github.com/ethereum/go-ethereum/accounts/abi" + ocr2types "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +// MerklePayloadTypes is the ABI of the payload an EVM Merkle delivery is +// verified with. It starts with the same five fields as PayloadTypes, so the +// verifier proxy routes it by reportContext[0], the config digest, and the fee +// manager reads the report from it unchanged. The Merkle fields follow. +// +// reportContext[1] holds MerkleReportContextTag in its first bytes and seqNr in +// its last 8. A legacy report context has 27 zero bytes there, so a verifier +// tells the two payloads apart by the tag. reportContext[2] is zero. +// +// The verifier rebuilds the leaf hash from channelId, reportFormat and report, +// hashes it up to the root with proof, and checks the signatures over +// protocol.MerkleSigningMessage(configDigest, seqNr, ReportFormatEVMMerkle, +// leafCount, root). A verifier without Merkle support recovers the wrong +// signers from such a payload and rejects it. +var MerklePayloadTypes = getMerklePayloadTypes() + +// MerkleReportContextTag marks reportContext[1] of a Merkle delivery payload. +const MerkleReportContextTag = protocol.MerkleSigningDomain + +func getMerklePayloadTypes() abi.Arguments { + mustNewType := func(t string) abi.Type { + result, err := abi.NewType(t, "", []abi.ArgumentMarshaling{}) + if err != nil { + panic(fmt.Sprintf("Unexpected error during abi.NewType: %s", err)) + } + return result + } + return append(slices.Clone(PayloadTypes), abi.Arguments([]abi.Argument{ + {Name: "leafCount", Type: mustNewType("uint32")}, + {Name: "leafIndex", Type: mustNewType("uint32")}, + {Name: "channelId", Type: mustNewType("uint32")}, + {Name: "reportFormat", Type: mustNewType("uint32")}, + {Name: "proof", Type: mustNewType("bytes32[]")}, + })...) +} + +// MerkleReportContext returns the report context of a Merkle delivery payload. +func MerkleReportContext(digest ocr2types.ConfigDigest, seqNr uint64) (rc [3][32]byte) { + rc[0] = [32]byte(digest) + copy(rc[1][:], MerkleReportContextTag) + binary.BigEndian.PutUint64(rc[1][24:], seqNr) + return rc +} + +// ReportCodecEVMMerkle packs ReportFormatEVMMerkle deliveries for EVM +// verifiers. It is a packer only: no channel uses the format, so there is +// nothing to encode. +type ReportCodecEVMMerkle struct{} + +// Pack assembles a delivery, as expanded from an attested bundle, and the root +// signatures into the payload for verifying on chain. +func (ReportCodecEVMMerkle) Pack(digest ocr2types.ConfigDigest, seqNr uint64, report ocr2types.Report, sigs []ocr2types.AttributedOnchainSignature) ([]byte, error) { + delivery, _, err := protocol.DecodeMerkleDelivery(report) + if err != nil { + return nil, err + } + if family := llotypes.ReportFormat(delivery.Family); family != llotypes.ReportFormatEVMMerkle { + return nil, fmt.Errorf("expected a delivery of family %s, got %s", llotypes.ReportFormatEVMMerkle, family) + } + proof := make([][32]byte, len(delivery.Proof)) + for i, p := range delivery.Proof { + proof[i] = [32]byte(p) + } + rs, ss, vs, err := splitSignatures(sigs) + if err != nil { + return nil, err + } + payload, err := MerklePayloadTypes.Pack( + MerkleReportContext(digest, seqNr), + delivery.Leaf.Report, + rs, + ss, + vs, + delivery.LeafCount, + delivery.LeafIndex, + delivery.Leaf.ChannelID, + delivery.Leaf.ReportFormat, + proof, + ) + if err != nil { + return nil, fmt.Errorf("abi.Pack failed; %w", err) + } + return payload, nil +} diff --git a/llo/reportcodec/evm/report_codec_evm_merkle_test.go b/llo/reportcodec/evm/report_codec_evm_merkle_test.go new file mode 100644 index 0000000..8fc90ad --- /dev/null +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -0,0 +1,129 @@ +package evm + +import ( + "crypto/ecdsa" + "encoding/binary" + "testing" + + "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + "github.com/smartcontractkit/libocr/commontypes" + ocr2types "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +// Test_ReportCodecEVMMerkle_Pack checks a packed delivery the way an onchain +// verifier would: rebuild the leaf from the payload, hash it up to the root +// with the proof, and recover the signers from the signed message. +func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { + digest := ocr2types.ConfigDigest{0x00, 0x09, 0xaa} + seqNr := uint64(42) + bundle := &protocol.LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*protocol.LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, + {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, + {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, + }, + } + root, err := protocol.MerkleBundleRoot(bundle) + require.NoError(t, err) + msg := protocol.MerkleSigningMessage(digest, seqNr, llotypes.ReportFormatEVMMerkle, uint32(len(bundle.Leaves)), root) + + keys := make([]*ecdsa.PrivateKey, 2) + sigs := make([]ocr2types.AttributedOnchainSignature, len(keys)) + for i := range keys { + keys[i], err = crypto.GenerateKey() + require.NoError(t, err) + sigs[i].Signature, err = crypto.Sign(msg[:], keys[i]) + require.NoError(t, err) + sigs[i].Signer = commontypes.OracleID(i) //nolint:gosec // test + } + + deliveries, err := protocol.ExpandMerkleBundle(bundle) + require.NoError(t, err) + for i, d := range deliveries { + report, err := protocol.EncodeMerkleDelivery(d) + require.NoError(t, err) + payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) + require.NoError(t, err) + + values, err := MerklePayloadTypes.Unpack(payload) + require.NoError(t, err) + require.Len(t, values, 10) + reportCtx := values[0].([3][32]byte) + leaf := &protocol.LLOMerkleLeafProto{ChannelID: values[7].(uint32), ReportFormat: values[8].(uint32), Report: values[1].([]byte)} + rs := values[2].([][32]byte) + ss := values[3].([][32]byte) + vs := values[4].([32]byte) + leafCount := values[5].(uint32) + leafIndex := values[6].(uint32) + proof := values[9].([][32]byte) + + gotDigest := reportCtx[0] + require.Equal(t, []byte(MerkleReportContextTag), reportCtx[1][:len(MerkleReportContextTag)]) + gotSeqNr := binary.BigEndian.Uint64(reportCtx[1][24:]) + assert.Equal(t, [32]byte{}, reportCtx[2]) + + assert.Equal(t, [32]byte(digest), gotDigest) + assert.Equal(t, seqNr, gotSeqNr) + assert.Equal(t, uint32(i), leafIndex) //nolint:gosec // test + assert.Equal(t, bundle.Leaves[i].Report, leaf.Report) + + proofBytes := make([][]byte, len(proof)) + for j := range proof { + proofBytes[j] = proof[j][:] + } + gotRoot, err := protocol.MerkleRootFromProof(protocol.MerkleLeafHash(llotypes.ReportFormatEVMMerkle, leaf), leafIndex, leafCount, proofBytes) + require.NoError(t, err) + require.Equal(t, root, gotRoot) + + gotMsg := protocol.MerkleSigningMessage(ocr2types.ConfigDigest(gotDigest), gotSeqNr, llotypes.ReportFormatEVMMerkle, leafCount, gotRoot) + require.Len(t, rs, len(keys)) + for j := range rs { + sig := append(append(append([]byte{}, rs[j][:]...), ss[j][:]...), vs[j]) + pub, err := crypto.SigToPub(gotMsg[:], sig) + require.NoError(t, err) + assert.Equal(t, crypto.PubkeyToAddress(keys[j].PublicKey), crypto.PubkeyToAddress(*pub)) + } + } + + // The fee manager and verifier proxy read a Merkle payload as a legacy + // one, and a verifier without Merkle support rejects it. + t.Run("decodes as a legacy payload and fails legacy verification", func(t *testing.T) { + report, err := protocol.EncodeMerkleDelivery(deliveries[1]) + require.NoError(t, err) + payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) + require.NoError(t, err) + + values, err := PayloadTypes.Unpack(payload) + require.NoError(t, err) + reportCtx := values[0].([3][32]byte) + reportData := values[1].([]byte) + assert.Equal(t, [32]byte(digest), [32]byte(payload[:32])) + assert.Equal(t, bundle.Leaves[1].Report, reportData) + + // A legacy report context has 27 zero bytes before epoch and round. + assert.NotEqual(t, make([]byte, 27), reportCtx[1][:27]) + + rs, ss, vs := values[2].([][32]byte), values[3].([][32]byte), values[4].([32]byte) + legacyHash := crypto.Keccak256(crypto.Keccak256(reportData), reportCtx[0][:], reportCtx[1][:], reportCtx[2][:]) + for j := range rs { + sig := append(append(append([]byte{}, rs[j][:]...), ss[j][:]...), vs[j]) + pub, err := crypto.SigToPub(legacyHash, sig) + require.NoError(t, err) + assert.NotEqual(t, crypto.PubkeyToAddress(keys[j].PublicKey), crypto.PubkeyToAddress(*pub)) + } + }) + + t.Run("rejects an invalid delivery", func(t *testing.T) { + _, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, []byte{0xff}, sigs) + require.Error(t, err) + }) +} diff --git a/llo/reportcodec/evm/report_codec_premium_legacy.go b/llo/reportcodec/evm/report_codec_premium_legacy.go index 5089f75..d8f18c3 100644 --- a/llo/reportcodec/evm/report_codec_premium_legacy.go +++ b/llo/reportcodec/evm/report_codec_premium_legacy.go @@ -183,20 +183,9 @@ func (r ReportCodecPremiumLegacy) Decode(b []byte) (*v3.Report, error) { // Pack assembles the report values into a payload for verifying on-chain func (r ReportCodecPremiumLegacy) Pack(digest types.ConfigDigest, seqNr uint64, report ocr2types.Report, sigs []types.AttributedOnchainSignature) ([]byte, error) { - var rs [][32]byte - var ss [][32]byte - var vs [32]byte - if len(sigs) > len(vs) { - return nil, fmt.Errorf("too many signatures; max: %d, got: %d", len(vs), len(sigs)) - } - for i, as := range sigs { - r, s, v, err := evmutil.SplitSignature(as.Signature) //nolint:revive // This has always worked before; no need to change it - if err != nil { - return nil, fmt.Errorf("eventTransmit(ev): error in SplitSignature: %w", err) - } - rs = append(rs, r) - ss = append(ss, s) - vs[i] = v + rs, ss, vs, err := splitSignatures(sigs) + if err != nil { + return nil, err } reportCtx, err := LegacyReportContext(digest, seqNr, r.donID) if err != nil { @@ -211,6 +200,24 @@ func (r ReportCodecPremiumLegacy) Pack(digest types.ConfigDigest, seqNr uint64, return payload, nil } +// splitSignatures splits EVM signatures into the r, s and v arrays the onchain +// verifiers take. +func splitSignatures(sigs []types.AttributedOnchainSignature) (rs, ss [][32]byte, vs [32]byte, err error) { + if len(sigs) > len(vs) { + return nil, nil, vs, fmt.Errorf("too many signatures; max: %d, got: %d", len(vs), len(sigs)) + } + for i, as := range sigs { + r, s, v, err := evmutil.SplitSignature(as.Signature) //nolint:revive // This has always worked before; no need to change it + if err != nil { + return nil, nil, vs, fmt.Errorf("eventTransmit(ev): error in SplitSignature: %w", err) + } + rs = append(rs, r) + ss = append(ss, s) + vs[i] = v + } + return rs, ss, vs, nil +} + // ExtractReportValues extracts the native price, link price and quote from the report // Can handle either *Decimal or *Quote types for native/link prices func ExtractReportValues(report protocol.Report) (nativePrice, linkPrice decimal.Decimal, quote *protocol.Quote, err error) { diff --git a/llo/transmitter/dataengine/server.go b/llo/transmitter/dataengine/server.go index f986d91..f3c2d22 100644 --- a/llo/transmitter/dataengine/server.go +++ b/llo/transmitter/dataengine/server.go @@ -95,6 +95,7 @@ type server struct { evmPremiumLegacyPacker ReportPacker evmStreamlinedPacker ReportPacker + evmMerklePacker ReportPacker jsonPacker ReportPacker transmitSuccessCount prometheus.Counter @@ -136,6 +137,7 @@ func newServer(lggr logger.Logger, verboseLogging bool, cfg QueueConfig, client serverURL, evm.NewReportCodecPremiumLegacy(codecLggr, pm.DonID()), evm.NewReportCodecStreamlined(codecLggr), + evm.ReportCodecEVMMerkle{}, reportcodec.JSONReportCodec{}, promTransmitSuccessCount.WithLabelValues(donIDStr, serverURL), promTransmitDuplicateCount.WithLabelValues(donIDStr, serverURL), @@ -327,6 +329,8 @@ func (s *server) transmit(ctx context.Context, t *Transmission) (*rpc.TransmitRe payload, err = s.evmPremiumLegacyPacker.Pack(t.ConfigDigest, t.SeqNr, t.Report.Report, t.Sigs) case llotypes.ReportFormatEVMStreamlined: payload, err = s.evmStreamlinedPacker.Pack(t.ConfigDigest, t.SeqNr, t.Report.Report, t.Sigs) + case llotypes.ReportFormatEVMMerkle: + payload, err = s.evmMerklePacker.Pack(t.ConfigDigest, t.SeqNr, t.Report.Report, t.Sigs) default: return nil, nil, fmt.Errorf("Transmit failed; don't know how to Pack unsupported report format: %q", t.Report.Info.ReportFormat) } diff --git a/llo/transmitter/dataengine/server_merkle_test.go b/llo/transmitter/dataengine/server_merkle_test.go new file mode 100644 index 0000000..c3ef2a6 --- /dev/null +++ b/llo/transmitter/dataengine/server_merkle_test.go @@ -0,0 +1,98 @@ +package dataengine + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" + "github.com/smartcontractkit/chainlink-data-streams/llo/reportcodec/evm" + "github.com/smartcontractkit/chainlink-data-streams/rpc" +) + +func Test_server_transmit_EVMMerkle(t *testing.T) { + var got *rpc.TransmitRequest + s := &server{ + evmMerklePacker: evm.ReportCodecEVMMerkle{}, + c: &MockGRPCClient{TransmitF: func(_ context.Context, in *rpc.TransmitRequest) (*rpc.TransmitResponse, error) { + got = in + return &rpc.TransmitResponse{}, nil + }}, + } + + bundle := &protocol.LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*protocol.LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, + }, + } + deliveries, err := protocol.ExpandMerkleBundle(bundle) + require.NoError(t, err) + delivery, err := protocol.EncodeMerkleDelivery(deliveries[1]) + require.NoError(t, err) + + transmission := &Transmission{ + ConfigDigest: types.ConfigDigest{1}, + SeqNr: 7, + Report: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: delivery, + Info: llotypes.ReportInfo{LifeCycleStage: protocol.LifeCycleStageProduction, ReportFormat: llotypes.ReportFormatEVMMerkle}, + }, + Sigs: []types.AttributedOnchainSignature{{Signature: make([]byte, 65), Signer: 1}}, + } + _, _, err = s.transmit(t.Context(), transmission) + require.NoError(t, err) + + require.NotNil(t, got) + assert.Equal(t, uint32(llotypes.ReportFormatEVMMerkle), got.ReportFormat) + want, err := evm.ReportCodecEVMMerkle{}.Pack(transmission.ConfigDigest, transmission.SeqNr, delivery, transmission.Sigs) + require.NoError(t, err) + assert.Equal(t, want, got.Payload) +} + +func Test_transmitter_TransmitBatch(t *testing.T) { + mt := &transmitter{ + lggr: logger.Sugared(logger.Test(t)), + servers: map[string]*server{"a": {}, "b": {}}, + commitCh: make(chan []*Transmission, 1), + } + + reports := make([]ocr3types.ReportWithInfo[llotypes.ReportInfo], 3) + for i := range reports { + reports[i] = ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: []byte{byte(i)}, + Info: llotypes.ReportInfo{ReportFormat: llotypes.ReportFormatEVMMerkle}, + } + } + + require.EqualError(t, mt.TransmitBatch(t.Context(), types.ConfigDigest{1}, 7, reports, nil), "transmitter is not started") + + require.NoError(t, mt.StartOnce("LLOMercuryTransmitter", func() error { return nil })) + require.NoError(t, mt.TransmitBatch(t.Context(), types.ConfigDigest{1}, 7, reports, nil)) + + // One send carries every report for every server. + require.Len(t, mt.commitCh, 1) + batch := <-mt.commitCh + require.Len(t, batch, len(reports)*len(mt.servers)) + perServer := map[string]int{} + for _, tr := range batch { + perServer[tr.ServerURL]++ + assert.Equal(t, uint64(7), tr.SeqNr) + } + assert.Equal(t, map[string]int{"a": 3, "b": 3}, perServer) + + // A full commit channel fails the batch once the context is done. + mt.commitCh <- nil + ctx, cancel := context.WithCancel(t.Context()) + cancel() + require.ErrorContains(t, mt.TransmitBatch(ctx, types.ConfigDigest{1}, 7, reports, nil), "failed to add transmission batch to commit channel") +} diff --git a/llo/transmitter/dataengine/transmitter.go b/llo/transmitter/dataengine/transmitter.go index 1ed8c7e..8a9be08 100644 --- a/llo/transmitter/dataengine/transmitter.go +++ b/llo/transmitter/dataengine/transmitter.go @@ -124,7 +124,9 @@ type transmitter struct { stopCh services.StopChan wg *sync.WaitGroup - commitCh chan *Transmission + // commitCh carries transmissions to the commit loops, one per send for + // Transmit and a whole batch per send for TransmitBatch. + commitCh chan []*Transmission } type Opts struct { @@ -160,7 +162,7 @@ func newTransmitter(opts Opts) *transmitter { opts.FromAccount, make(services.StopChan), &sync.WaitGroup{}, - make(chan *Transmission, 1000*len(servers)), + make(chan []*Transmission, 1000*len(servers)), } } @@ -263,7 +265,7 @@ func (mt *transmitter) Transmit( Sigs: sigs, } select { - case mt.commitCh <- t: + case mt.commitCh <- []*Transmission{t}: case <-ctx.Done(): err = fmt.Errorf("failed to add transmission to commit channel: %w", ctx.Err()) } @@ -277,6 +279,44 @@ func (mt *transmitter) Transmit( return err } +// TransmitBatch enqueues reports that share a digest, seqNr and signatures, +// such as the deliveries of one Merkle bundle, for every server in one send +// to the commit loops. Like Transmit it returns once the batch is queued, so a +// large batch costs one channel slot rather than one per report. +func (mt *transmitter) TransmitBatch( + ctx context.Context, + digest types.ConfigDigest, + seqNr uint64, + reports []ocr3types.ReportWithInfo[llotypes.ReportInfo], + sigs []types.AttributedOnchainSignature, +) (err error) { + ok := mt.IfStarted(func() { + transmissions := make([]*Transmission, 0, len(reports)*len(mt.servers)) + for serverURL := range mt.servers { + for _, report := range reports { + transmissions = append(transmissions, &Transmission{ + ServerURL: serverURL, + ConfigDigest: digest, + SeqNr: seqNr, + Report: report, + Sigs: sigs, + }) + } + } + select { + case mt.commitCh <- transmissions: + case <-ctx.Done(): + err = fmt.Errorf("failed to add transmission batch to commit channel: %w", ctx.Err()) + } + }) + + if !ok { + return errors.New("transmitter is not started") + } + + return err +} + func (mt *transmitter) transmit(ctx context.Context, transmissions []*Transmission) error { // On shutdown appears that libocr can pass us a pre-canceled context; // don't even bother trying to insert/transmit in this case @@ -376,8 +416,8 @@ func (mt *transmitter) spawnCommitLoops() { transmissions = make([]*Transmission, 0, buff) } - case t := <-mt.commitCh: - transmissions = append(transmissions, t) + case batch := <-mt.commitCh: + transmissions = append(transmissions, batch...) if len(transmissions) >= buff { err = mt.transmit(ctx, transmissions) transmissions = make([]*Transmission, 0, buff) diff --git a/llo/transmitter/transmitter.go b/llo/transmitter/transmitter.go index b2158ff..9bd3689 100644 --- a/llo/transmitter/transmitter.go +++ b/llo/transmitter/transmitter.go @@ -2,6 +2,7 @@ package transmitter import ( "context" + "errors" "fmt" "runtime/debug" "sync" @@ -42,6 +43,12 @@ type Transmitter interface { services.Service } +// batchTransmitter is a sub transmitter that can take the deliveries of one +// Merkle bundle at once, rather than one report per call. +type batchTransmitter interface { + TransmitBatch(ctx context.Context, digest types.ConfigDigest, seqNr uint64, reports []ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature) error +} + type TransmitterRetirementReportCacheWriter interface { StoreAttestedRetirementReport(ctx context.Context, cd ocrtypes.ConfigDigest, seqNr uint64, retirementReport []byte, sigs []types.AttributedOnchainSignature) error } @@ -182,6 +189,10 @@ func (t *transmitter) Transmit( return nil } + if protocol.IsMerkleFamily(report.Info.ReportFormat) { + return t.transmitMerkleBundle(ctx, digest, seqNr, report, sigs) + } + g := new(errgroup.Group) for _, st := range t.subTransmitters { g.Go(func() error { @@ -191,6 +202,60 @@ func (t *transmitter) Transmit( return g.Wait() } +// transmitMerkleBundle hands every delivery of an attested bundle to each sub +// transmitter. libocr calls Transmit once for the whole bundle, under one +// deadline, so a sub transmitter that takes a batch gets all of them in one +// call. One that does not gets them one at a time, and every delivery is +// attempted even when an earlier one fails. +func (t *transmitter) transmitMerkleBundle(ctx context.Context, digest types.ConfigDigest, seqNr uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature) error { + reports, err := expandMerkleBundle(report) + if err != nil { + return err + } + + g := new(errgroup.Group) + for _, st := range t.subTransmitters { + g.Go(func() error { + if bt, ok := st.(batchTransmitter); ok { + return bt.TransmitBatch(ctx, digest, seqNr, reports, sigs) + } + var errs error + for _, r := range reports { + errs = errors.Join(errs, st.Transmit(ctx, digest, seqNr, r, sigs)) + } + return errs + }) + } + return g.Wait() +} + +// expandMerkleBundle turns an attested bundle into one delivery per leaf. Each +// delivery carries the leaf and its proof to the root the signatures cover, so +// sub transmitters persist and send it like any other report, under the +// family's report format. +func expandMerkleBundle(report ocr3types.ReportWithInfo[llotypes.ReportInfo]) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) { + bundle, err := protocol.DecodeMerkleBundle(report.Report) + if err != nil { + return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) + } + if llotypes.ReportFormat(bundle.Family) != report.Info.ReportFormat { + return nil, fmt.Errorf("failed to expand %s bundle: bundle is of family %s", report.Info.ReportFormat, llotypes.ReportFormat(bundle.Family)) + } + deliveries, err := protocol.ExpandMerkleBundle(bundle) + if err != nil { + return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) + } + reports := make([]ocr3types.ReportWithInfo[llotypes.ReportInfo], len(deliveries)) + for i, delivery := range deliveries { + encoded, err := protocol.EncodeMerkleDelivery(delivery) + if err != nil { + return nil, fmt.Errorf("failed to encode %s delivery: %w", report.Info.ReportFormat, err) + } + reports[i] = ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: report.Info} + } + return reports, nil +} + // FromAccount returns the stringified (hex) CSA public key func (t *transmitter) FromAccount(ctx context.Context) (ocr2types.Account, error) { return ocr2types.Account(t.fromAccount), nil diff --git a/llo/transmitter/transmitter_merkle_test.go b/llo/transmitter/transmitter_merkle_test.go new file mode 100644 index 0000000..b6ef448 --- /dev/null +++ b/llo/transmitter/transmitter_merkle_test.go @@ -0,0 +1,131 @@ +package transmitter + +import ( + "context" + "errors" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services" + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" + "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +type recordingSubTransmitter struct { + services.Service + mu sync.Mutex + reports []ocr3types.ReportWithInfo[llotypes.ReportInfo] + sigs [][]types.AttributedOnchainSignature +} + +func (r *recordingSubTransmitter) Transmit(_ context.Context, _ types.ConfigDigest, _ uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature) error { + r.mu.Lock() + defer r.mu.Unlock() + r.reports = append(r.reports, report) + r.sigs = append(r.sigs, sigs) + return nil +} + +func (r *recordingSubTransmitter) FromAccount(context.Context) (types.Account, error) { + return "", nil +} + +// batchingSubTransmitter takes a bundle's deliveries in one call. +type batchingSubTransmitter struct { + recordingSubTransmitter + batches [][]ocr3types.ReportWithInfo[llotypes.ReportInfo] +} + +func (b *batchingSubTransmitter) TransmitBatch(_ context.Context, _ types.ConfigDigest, _ uint64, reports []ocr3types.ReportWithInfo[llotypes.ReportInfo], _ []types.AttributedOnchainSignature) error { + b.mu.Lock() + defer b.mu.Unlock() + b.batches = append(b.batches, reports) + return nil +} + +// failingSubTransmitter fails its first transmission. +type failingSubTransmitter struct { + recordingSubTransmitter +} + +func (f *failingSubTransmitter) Transmit(_ context.Context, _ types.ConfigDigest, _ uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], _ []types.AttributedOnchainSignature) error { + f.mu.Lock() + defer f.mu.Unlock() + f.reports = append(f.reports, report) + if len(f.reports) == 1 { + return errors.New("first fails") + } + return nil +} + +func Test_transmitter_ExpandsMerkleBundle(t *testing.T) { + ctx := t.Context() + subs := []*recordingSubTransmitter{{}, {}} + tr := &transmitter{ + lggr: logger.Test(t), + subTransmitters: []Transmitter{subs[0], subs[1]}, + onTransmit: &onTransmit{lggr: logger.Test(t)}, + } + + bundle := &protocol.LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*protocol.LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, + {ChannelID: 5, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte("five")}, + }, + } + encoded, err := protocol.EncodeMerkleBundle(bundle) + require.NoError(t, err) + root, err := protocol.MerkleBundleRoot(bundle) + require.NoError(t, err) + info := llotypes.ReportInfo{LifeCycleStage: protocol.LifeCycleStageProduction, ReportFormat: llotypes.ReportFormatEVMMerkle} + sigs := []types.AttributedOnchainSignature{{Signature: []byte{1}, Signer: 0}, {Signature: []byte{2}, Signer: 3}} + + require.NoError(t, tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: info}, sigs)) + + for _, sub := range subs { + require.Len(t, sub.reports, len(bundle.Leaves)) + for i, r := range sub.reports { + assert.Equal(t, info, r.Info) + assert.Equal(t, sigs, sub.sigs[i]) + delivery, got, err := protocol.DecodeMerkleDelivery(r.Report) + require.NoError(t, err) + assert.Equal(t, root, got, "delivery %d does not reach the signed root", i) + assert.Equal(t, uint32(i), delivery.LeafIndex) //nolint:gosec // test + assert.Equal(t, bundle.Leaves[i].ChannelID, delivery.Leaf.ChannelID) + } + } + + t.Run("a batching sub transmitter gets every delivery in one call", func(t *testing.T) { + sub := &batchingSubTransmitter{} + tr := &transmitter{lggr: logger.Test(t), subTransmitters: []Transmitter{sub}, onTransmit: &onTransmit{lggr: logger.Test(t)}} + require.NoError(t, tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: info}, sigs)) + require.Len(t, sub.batches, 1) + assert.Len(t, sub.batches[0], len(bundle.Leaves)) + assert.Empty(t, sub.reports) + }) + + t.Run("a failed delivery does not drop the rest", func(t *testing.T) { + sub := &failingSubTransmitter{} + tr := &transmitter{lggr: logger.Test(t), subTransmitters: []Transmitter{sub}, onTransmit: &onTransmit{lggr: logger.Test(t)}} + err := tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: info}, sigs) + require.EqualError(t, err, "first fails") + assert.Len(t, sub.reports, len(bundle.Leaves)) + }) + + t.Run("an invalid bundle is not transmitted", func(t *testing.T) { + sub := &recordingSubTransmitter{} + tr := &transmitter{lggr: logger.Test(t), subTransmitters: []Transmitter{sub}, onTransmit: &onTransmit{lggr: logger.Test(t)}} + err := tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: []byte{0xff}, Info: info}, sigs) + require.ErrorContains(t, err, "failed to expand evm_merkle bundle") + assert.Empty(t, sub.reports) + }) +} diff --git a/llo/v30/plugin_codecs_test.go b/llo/v30/plugin_codecs_test.go index 54500a5..0bc18fc 100644 --- a/llo/v30/plugin_codecs_test.go +++ b/llo/v30/plugin_codecs_test.go @@ -68,6 +68,8 @@ func genChannelDefinition() gopter.Gen { "Tombstone": gen.Bool(), "Source": gen.UInt32(), "DisableNilStreamValues": gen.Bool(), + // v30 clears SigningScheme on input and never carries it. + "SigningScheme": gen.Const(llotypes.SigningSchemeDefault), }) } diff --git a/llo/v30/plugin_observation.go b/llo/v30/plugin_observation.go index 104d810..7b56bfe 100644 --- a/llo/v30/plugin_observation.go +++ b/llo/v30/plugin_observation.go @@ -79,7 +79,10 @@ func (p *Plugin) observation(ctx context.Context, outctx ocr3types.OutcomeContex // can agree on the same set of changes. // // ChannelIDs should always be sorted the same way (channel ID ascending). - expectedChannelDefs := p.ChannelDefinitionCache.Definitions(previousOutcome.ChannelDefinitions) + expectedChannelDefs, unsupported := withoutSigningSchemes(previousOutcome.ChannelDefinitions, p.ChannelDefinitionCache.Definitions(previousOutcome.ChannelDefinitions)) + if len(unsupported) > 0 { + p.Logger.Errorw("ChannelDefinitionCache.Definitions has channels with a signing scheme, which LLO v30 does not support, not voting for them", "channelIDs", unsupported) + } // Only the channels this node would vote to add or change are held // to the admission-only checks; the ones already committed are not, // or a grandfathered channel would freeze channel voting entirely. @@ -217,3 +220,33 @@ func sortChannelIDs(cids []llotypes.ChannelID) { return cids[i] < cids[j] }) } + +// withoutSigningSchemes returns expected with every channel that sets a +// SigningScheme reverted to its committed definition, or left out if it has +// none, and the reverted channel IDs in ascending order. v30 signs every report +// on its own, so it never votes for such a channel, which a channel +// definitions cache shared with a v31 instance can hold. +func withoutSigningSchemes(committed, expected llotypes.ChannelDefinitions) (llotypes.ChannelDefinitions, []llotypes.ChannelID) { + var out llotypes.ChannelDefinitions + var unsupported []llotypes.ChannelID + for channelID, cd := range expected { + if cd.SigningScheme == llotypes.SigningSchemeDefault { + continue + } + if out == nil { + // expected may share its backing map with the previous outcome. + out = maps.Clone(expected) + } + if prev, ok := committed[channelID]; ok && prev.SigningScheme == llotypes.SigningSchemeDefault { + out[channelID] = prev + } else { + delete(out, channelID) + } + unsupported = append(unsupported, channelID) + } + if out == nil { + return expected, nil + } + sort.Slice(unsupported, func(i, j int) bool { return unsupported[i] < unsupported[j] }) + return out, unsupported +} diff --git a/llo/v30/plugin_test.go b/llo/v30/plugin_test.go index 7306cca..69bfb22 100644 --- a/llo/v30/plugin_test.go +++ b/llo/v30/plugin_test.go @@ -155,3 +155,23 @@ func Test_NewReportingPlugin_setsValues(t *testing.T) { assert.Equal(t, uint64(12345), p.(*Plugin).DefaultMinReportIntervalNanoseconds) }) } + +func Test_withoutSigningSchemes(t *testing.T) { + plain := llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMABIEncodeUnpacked} + merkle := plain + merkle.SigningScheme = llotypes.SigningSchemeMerkle + + committed := llotypes.ChannelDefinitions{1: plain, 2: plain} + + got, unsupported := withoutSigningSchemes(committed, committed) + assert.Equal(t, committed, got) + assert.Empty(t, unsupported) + + // A committed channel switched to a scheme keeps its committed + // definition, and a new channel with a scheme is left out. + expected := llotypes.ChannelDefinitions{1: plain, 2: merkle, 3: merkle} + got, unsupported = withoutSigningSchemes(committed, expected) + assert.Equal(t, llotypes.ChannelDefinitions{1: plain, 2: plain}, got) + assert.Equal(t, []llotypes.ChannelID{2, 3}, unsupported) + assert.Equal(t, merkle, expected[2], "the input must not be modified") +} From 1d448f68d40809c9231b69032dfad6077aec559f Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Wed, 4 Nov 2026 15:01:30 +0000 Subject: [PATCH 3/9] llo: harden Merkle bundling, transmission and v30 admission Chunk transmit queue inserts below the Postgres bind parameter limit. Exclude EVMStreamlined from the EVM Merkle family current verifiers do not support EVMStreamlined. Revert v30 backfill channels whose target is reverted for its signing scheme. Drop only the failing family when a Merkle bundle fails to encode. Capture report telemetry only for emitted reports. Correct the bundle leaf order documented in llo_merkle.proto. Extract protocol.SigningFamily and v31 MaxReportBytes, and make Transmit delegate to TransmitBatch. --- llo/dev/v31/doc.go | 7 +- llo/dev/v31/factory.go | 6 +- llo/dev/v31/merkle.go | 89 +++++++++---------- llo/dev/v31/merkle_test.go | 29 ++++-- llo/dev/v31/reports.go | 23 +++-- llo/protocol/llo_merkle.pb.go | 6 +- llo/protocol/llo_merkle.proto | 6 +- llo/protocol/merkle.go | 44 +++++---- llo/protocol/merkle_test.go | 35 ++++---- .../evm/report_codec_evm_merkle_test.go | 2 +- llo/transmitter/dataengine/orm.go | 16 ++-- llo/transmitter/dataengine/orm_test.go | 18 ++++ .../dataengine/server_merkle_test.go | 2 +- llo/transmitter/dataengine/transmitter.go | 29 +----- llo/transmitter/transmitter_merkle_test.go | 2 +- llo/v30/plugin_observation.go | 34 +++++-- llo/v30/plugin_test.go | 19 ++++ 17 files changed, 222 insertions(+), 145 deletions(-) diff --git a/llo/dev/v31/doc.go b/llo/dev/v31/doc.go index 7e68c42..50522b4 100644 --- a/llo/dev/v31/doc.go +++ b/llo/dev/v31/doc.go @@ -209,9 +209,10 @@ // delivery per channel with its proof. See protocol/merkle.go for the tree and // the signed message. // -// The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers every -// format in llo/reportcodec/evm. Backfill reports follow the scheme of their -// target channel. +// The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers the +// formats in llo/reportcodec/evm whose reports start with the feed ID, so every +// one but EVMStreamlined. Backfill reports follow the scheme of their target +// channel. // // A family is not tied to a destination chain. It fixes one signing key, one // hash and signature scheme, and one delivery packer. The root is signed once diff --git a/llo/dev/v31/factory.go b/llo/dev/v31/factory.go index 4e1a91c..756afe8 100644 --- a/llo/dev/v31/factory.go +++ b/llo/dev/v31/factory.go @@ -228,7 +228,7 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re MaxQueryBytes: MaxMaxQueryBytesUnused, MaxObservationBytes: ocr3_1types.MaxMaxObservationBytes, MaxReportsPlusPrecursorBytes: ocr3_1types.MaxMaxReportsPlusPrecursorBytes, - MaxReportBytes: ocr3_1types.MaxMaxReportBytes, + MaxReportBytes: MaxReportBytes, MaxReportCount: protocol.MaxReportCount, MaxKeyValueModifiedKeys: ocr3_1types.MaxMaxKeyValueModifiedKeys, @@ -257,3 +257,7 @@ func (f *PluginFactory) NewReportingPlugin(ctx context.Context, cfg ocr3types.Re // MaxMaxQueryBytesUnused documents that LLO uses an empty query. const MaxMaxQueryBytesUnused = 0 + +// MaxReportBytes is the largest report the plugin emits. A Merkle bundle is one +// report, so the bundler splits by it. +const MaxReportBytes = ocr3_1types.MaxMaxReportBytes diff --git a/llo/dev/v31/merkle.go b/llo/dev/v31/merkle.go index 0818afa..bb5ff80 100644 --- a/llo/dev/v31/merkle.go +++ b/llo/dev/v31/merkle.go @@ -1,70 +1,51 @@ package llo import ( - "fmt" "slices" llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" - "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types" "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" ) -// merkleBundleMaxBytes is the MaxReportBytes NewReportingPlugin declares. A -// bundle is one report, so it must fit in it. -const merkleBundleMaxBytes = ocr3_1types.MaxMaxReportBytes - // merkleBundler collects the channel reports of a round that are signed as // leaves, per signing family. type merkleBundler struct { - leaves map[llotypes.ReportFormat][]*protocol.LLOMerkleLeafProto - // sources are the reportable channels the leaves were emitted for, in leaf - // order. It differs from the leaf channel ID for backfill reports. - sources map[llotypes.ReportFormat][]llotypes.ChannelID + leaves map[llotypes.ReportFormat][]bundlerLeaf +} + +type bundlerLeaf struct { + leaf *protocol.LLOMerkleLeafProto + // source is the reportable channel the leaf was emitted for. It differs + // from the leaf channel ID for backfill reports. + source llotypes.ChannelID + // emitted captures the report telemetry once the leaf is in a bundle. + emitted func() } // add records the report encoded for channelID in format as a leaf of family. -func (b *merkleBundler) add(family llotypes.ReportFormat, source, channelID llotypes.ChannelID, format llotypes.ReportFormat, report []byte) { +func (b *merkleBundler) add(family llotypes.ReportFormat, source, channelID llotypes.ChannelID, format llotypes.ReportFormat, report []byte, emitted func()) { if b.leaves == nil { - b.leaves = map[llotypes.ReportFormat][]*protocol.LLOMerkleLeafProto{} - b.sources = map[llotypes.ReportFormat][]llotypes.ChannelID{} + b.leaves = map[llotypes.ReportFormat][]bundlerLeaf{} } - b.leaves[family] = append(b.leaves[family], &protocol.LLOMerkleLeafProto{ - ChannelID: channelID, - ReportFormat: uint32(format), - Report: report, + b.leaves[family] = append(b.leaves[family], bundlerLeaf{ + leaf: &protocol.LLOMerkleLeafProto{ + ChannelID: channelID, + ReportFormat: uint32(format), + Report: report, + }, + source: source, + emitted: emitted, }) - b.sources[family] = append(b.sources[family], source) -} - -// signingFamily decides how the report of a channel encoded with cd is signed. -// It returns the family when the report is a leaf, and false when it is signed -// on its own. A scheme the instance cannot sign with returns an error and the -// report is not emitted. -// -// Baseline verification keeps such a scheme out of the committed set. The -// error path only guards against it getting there anyway. -func (p *Plugin) signingFamily(cd llotypes.ChannelDefinition) (llotypes.ReportFormat, bool, error) { - switch cd.SigningScheme { - case llotypes.SigningSchemeDefault: - return 0, false, nil - case llotypes.SigningSchemeMerkle: - family, ok := protocol.MerkleFamily(cd.ReportFormat) - if !ok { - return 0, false, fmt.Errorf("report format %s has no signing family", cd.ReportFormat) - } - return family, true, nil - default: - return 0, false, fmt.Errorf("unknown signing scheme %q", cd.SigningScheme) - } } // bundles returns one bundle report per family, split by size, in family // order. Leaves are in the order they were added, which is ascending -// reportable channel ID. -func (b *merkleBundler) bundles(p *Plugin, seqNr uint64, stage llotypes.LifeCycleStage) ([]ocr3types.ReportPlus[llotypes.ReportInfo], error) { +// reportable channel ID. A family that fails to encode emits none of its +// leaves, and the other families are unaffected. +func (b *merkleBundler) bundles(p *Plugin, seqNr uint64, stage llotypes.LifeCycleStage) []ocr3types.ReportPlus[llotypes.ReportInfo] { families := make([]llotypes.ReportFormat, 0, len(b.leaves)) for family := range b.leaves { families = append(families, family) @@ -73,13 +54,27 @@ func (b *merkleBundler) bundles(p *Plugin, seqNr uint64, stage llotypes.LifeCycl var rwis []ocr3types.ReportPlus[llotypes.ReportInfo] for _, family := range families { - encoded, oversized, err := protocol.SplitMerkleBundle(family, b.leaves[family], merkleBundleMaxBytes) + pending := b.leaves[family] + leaves := make([]*protocol.LLOMerkleLeafProto, len(pending)) + for i, l := range pending { + leaves[i] = l.leaf + } + encoded, oversized, err := protocol.SplitMerkleBundle(family, leaves, MaxReportBytes) if err != nil { - return nil, fmt.Errorf("error encoding %s bundle: %w", family, err) + for _, l := range pending { + p.reportNotEmitted(seqNr, l.source, llotypes.ReportFormat(l.leaf.ReportFormat), "merkle_bundle_encode_failed", "family", family, "err", err) + } + continue } for _, i := range oversized { - leaf := b.leaves[family][i] - p.reportNotEmitted(seqNr, b.sources[family][i], llotypes.ReportFormat(leaf.ReportFormat), "merkle_leaf_too_large", "reportBytes", len(leaf.Report)) + l := pending[i] + p.reportNotEmitted(seqNr, l.source, llotypes.ReportFormat(l.leaf.ReportFormat), "merkle_leaf_too_large", "reportBytes", len(l.leaf.Report)) + pending[i].emitted = nil + } + for _, l := range pending { + if l.emitted != nil { + l.emitted() + } } for _, bundle := range encoded { rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ @@ -93,5 +88,5 @@ func (b *merkleBundler) bundles(p *Plugin, seqNr uint64, stage llotypes.LifeCycl }) } } - return rwis, nil + return rwis } diff --git a/llo/dev/v31/merkle_test.go b/llo/dev/v31/merkle_test.go index ce8d104..13eecef 100644 --- a/llo/dev/v31/merkle_test.go +++ b/llo/dev/v31/merkle_test.go @@ -89,7 +89,7 @@ func Test_Reports_MerkleBundle(t *testing.T) { defs := llotypes.ChannelDefinitions{ 1: merkleChannel(llotypes.ReportFormatJSON, llotypes.SigningSchemeDefault), 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), - 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), 4: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeDefault), 5: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), } @@ -112,7 +112,7 @@ func Test_Reports_MerkleBundle(t *testing.T) { format llotypes.ReportFormat }{ {2, llotypes.ReportFormatEVMABIEncodeUnpacked}, - {3, llotypes.ReportFormatEVMStreamlined}, + {3, llotypes.ReportFormatEVMPremiumLegacy}, {5, llotypes.ReportFormatEVMPremiumLegacy}, } { leaf := bundle.Leaves[i] @@ -149,11 +149,11 @@ func Test_Reports_MerkleBundle(t *testing.T) { func Test_Reports_MerkleBundleSplitsBySize(t *testing.T) { // Three reports of 40% of the report size limit fit two to a bundle. - p := merklePlugin(t, leafCodec{size: merkleBundleMaxBytes * 4 / 10}) + p := merklePlugin(t, leafCodec{size: MaxReportBytes * 4 / 10}) defs := llotypes.ChannelDefinitions{ 1: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), - 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), } rwis, err := p.Reports(t.Context(), 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) require.NoError(t, err) @@ -161,10 +161,29 @@ func Test_Reports_MerkleBundleSplitsBySize(t *testing.T) { var ids []llotypes.ChannelID for _, rwi := range rwis { - assert.LessOrEqual(t, len(rwi.ReportWithInfo.Report), merkleBundleMaxBytes) + assert.LessOrEqual(t, len(rwi.ReportWithInfo.Report), MaxReportBytes) for _, leaf := range bundleOf(t, rwi).Leaves { ids = append(ids, leaf.ChannelID) } } assert.Equal(t, []llotypes.ChannelID{1, 2, 3}, ids) } + +func Test_Reports_MerkleOversizedLeafHasNoTelemetry(t *testing.T) { + p := merklePlugin(t, leafCodec{size: MaxReportBytes}) + rtCh := make(chan *protocol.LLOReportTelemetry, 8) + p.ReportTelemetryCh = rtCh + // Emitters with N=4, F=1 for seqNr 3 are {3, 0}. + p.OracleID = 0 + defs := llotypes.ChannelDefinitions{ + 1: merkleChannel(llotypes.ReportFormatJSON, llotypes.SigningSchemeDefault), + 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), + } + rwis, err := p.Reports(t.Context(), 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) + require.NoError(t, err) + require.Len(t, rwis, 1) + assert.Equal(t, llotypes.ReportFormatJSON, rwis[0].ReportWithInfo.Info.ReportFormat) + + require.Len(t, rtCh, 1) + assert.Equal(t, uint32(1), (<-rtCh).ChannelId) +} diff --git a/llo/dev/v31/reports.go b/llo/dev/v31/reports.go index e66f387..da75c04 100644 --- a/llo/dev/v31/reports.go +++ b/llo/dev/v31/reports.go @@ -112,7 +112,6 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t reportForEncode := report reportForEncode.ChannelID = opts.TargetChannelID - p.captureReportTelemetry(reportForEncode, targetCD, targetCD.Streams, out.LifeCycleStage) codec, exists := p.ReportCodecs[targetCD.ReportFormat] if !exists { p.reportNotEmitted(seqNr, cid, targetCD.ReportFormat, "codec_missing", "targetChannelID", opts.TargetChannelID) @@ -125,15 +124,17 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t } // The backfill report is signed like the target channel's own // reports, so its consumers verify both the same way. - family, leaf, err := p.signingFamily(targetCD) + family, leaf, err := protocol.SigningFamily(targetCD) if err != nil { p.reportNotEmitted(seqNr, cid, targetCD.ReportFormat, "signing_scheme_unsupported", "targetChannelID", opts.TargetChannelID, "err", err) continue } + emitted := func() { p.captureReportTelemetry(reportForEncode, targetCD, targetCD.Streams, out.LifeCycleStage) } if leaf { - bundler.add(family, cid, opts.TargetChannelID, targetCD.ReportFormat, encoded) + bundler.add(family, cid, opts.TargetChannelID, targetCD.ReportFormat, encoded, emitted) continue } + emitted() rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -167,8 +168,6 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t Specimen: out.LifeCycleStage != protocol.LifeCycleStageProduction, } - p.captureReportTelemetry(report, cd, streams, out.LifeCycleStage) - codec, exists := p.ReportCodecs[cd.ReportFormat] if !exists { p.reportNotEmitted(seqNr, cid, cd.ReportFormat, "codec_missing") @@ -179,15 +178,19 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t p.reportNotEmitted(seqNr, cid, cd.ReportFormat, "encode_failed", "err", encErr) continue } - family, leaf, err := p.signingFamily(cd) + family, leaf, err := protocol.SigningFamily(cd) if err != nil { p.reportNotEmitted(seqNr, cid, cd.ReportFormat, "signing_scheme_unsupported", "err", err) continue } + // Telemetry is captured only for a report that is emitted, which for a + // leaf is once it is in a bundle. + emitted := func() { p.captureReportTelemetry(report, cd, streams, out.LifeCycleStage) } if leaf { - bundler.add(family, cid, cid, cd.ReportFormat, encoded) + bundler.add(family, cid, cid, cd.ReportFormat, encoded, emitted) continue } + emitted() rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -199,11 +202,7 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t }) } - bundles, err := bundler.bundles(p, seqNr, out.LifeCycleStage) - if err != nil { - return nil, err - } - rwis = append(rwis, bundles...) + rwis = append(rwis, bundler.bundles(p, seqNr, out.LifeCycleStage)...) // The staging marker goes last, so the other reports keep their positions, // and only within the report count limit. diff --git a/llo/protocol/llo_merkle.pb.go b/llo/protocol/llo_merkle.pb.go index a1d60b3..9f1e41b 100644 --- a/llo/protocol/llo_merkle.pb.go +++ b/llo/protocol/llo_merkle.pb.go @@ -22,8 +22,10 @@ const ( ) // LLOMerkleBundleProto is the report a signing family signs once per round. -// Leaves are in ascending channel ID order. The root is not stored: every -// oracle and the keyring recompute it from the leaves. +// Leaves are in ascending order of the reportable channel that emitted them. +// A backfill leaf carries its target's channel ID, so leaf channel IDs are +// neither sorted nor unique. The root is not stored: every oracle and the +// keyring recompute it from the leaves. type LLOMerkleBundleProto struct { state protoimpl.MessageState `protogen:"open.v1"` Family uint32 `protobuf:"varint,1,opt,name=family,proto3" json:"family,omitempty"` diff --git a/llo/protocol/llo_merkle.proto b/llo/protocol/llo_merkle.proto index 0f12733..5abb917 100644 --- a/llo/protocol/llo_merkle.proto +++ b/llo/protocol/llo_merkle.proto @@ -10,8 +10,10 @@ option go_package = ".;protocol"; // and verified by the Data Streams server and onchain. // LLOMerkleBundleProto is the report a signing family signs once per round. -// Leaves are in ascending channel ID order. The root is not stored: every -// oracle and the keyring recompute it from the leaves. +// Leaves are in ascending order of the reportable channel that emitted them. +// A backfill leaf carries its target's channel ID, so leaf channel IDs are +// neither sorted nor unique. The root is not stored: every oracle and the +// keyring recompute it from the leaves. message LLOMerkleBundleProto { uint32 family = 1; repeated LLOMerkleLeafProto leaves = 2; diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go index c0db22c..adff0f0 100644 --- a/llo/protocol/merkle.go +++ b/llo/protocol/merkle.go @@ -48,15 +48,15 @@ type MerkleHash = [32]byte // MerkleFamily returns the signing family that channels in format join under // SigningSchemeMerkle, and false if format has none. // -// The EVM family covers every format with a codec in llo/reportcodec/evm. They -// all produce reports for EVM verifiers and hash with keccak256, so one bundle -// can hold all of them. +// The EVM family covers the formats in llo/reportcodec/evm whose reports start +// with the feed ID, as the fee manager reads them. They all hash with +// keccak256, so one bundle can hold all of them. EVMStreamlined reports are +// packed without that header and stay out. func MerkleFamily(format llotypes.ReportFormat) (llotypes.ReportFormat, bool) { switch format { case llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, - llotypes.ReportFormatEVMABIEncodeUnpackedExpr, - llotypes.ReportFormatEVMStreamlined: + llotypes.ReportFormatEVMABIEncodeUnpackedExpr: return llotypes.ReportFormatEVMMerkle, true default: return 0, false @@ -68,25 +68,33 @@ func IsMerkleFamily(format llotypes.ReportFormat) bool { return format == llotypes.ReportFormatEVMMerkle } -// VerifySigningScheme checks how a channel definition is signed. A signing -// family is never a channel format, the scheme must be empty or -// SigningSchemeMerkle, and SigningSchemeMerkle needs a format with a signing -// family. -func VerifySigningScheme(cd llotypes.ChannelDefinition) error { - if IsMerkleFamily(cd.ReportFormat) { - return fmt.Errorf("report format %s is a signing family, not a channel format", cd.ReportFormat) - } +// SigningFamily returns how the reports of a channel defined by cd are signed: +// the family they join as Merkle leaves and true, or false when each report is +// signed on its own. It fails for an unknown scheme, or SigningSchemeMerkle on +// a format with no signing family. +func SigningFamily(cd llotypes.ChannelDefinition) (llotypes.ReportFormat, bool, error) { switch cd.SigningScheme { case llotypes.SigningSchemeDefault: - return nil + return 0, false, nil case llotypes.SigningSchemeMerkle: - if _, ok := MerkleFamily(cd.ReportFormat); !ok { - return fmt.Errorf("signing scheme %q is not supported for report format %s", cd.SigningScheme, cd.ReportFormat) + family, ok := MerkleFamily(cd.ReportFormat) + if !ok { + return 0, false, fmt.Errorf("signing scheme %q is not supported for report format %s", cd.SigningScheme, cd.ReportFormat) } - return nil + return family, true, nil default: - return fmt.Errorf("unknown signing scheme %q", cd.SigningScheme) + return 0, false, fmt.Errorf("unknown signing scheme %q", cd.SigningScheme) + } +} + +// VerifySigningScheme checks how a channel definition is signed. A signing +// family is never a channel format, and SigningFamily must accept the scheme. +func VerifySigningScheme(cd llotypes.ChannelDefinition) error { + if IsMerkleFamily(cd.ReportFormat) { + return fmt.Errorf("report format %s is a signing family, not a channel format", cd.ReportFormat) } + _, _, err := SigningFamily(cd) + return err } func keccak(parts ...[]byte) (h MerkleHash) { diff --git a/llo/protocol/merkle_test.go b/llo/protocol/merkle_test.go index 4648ca7..46dc5b5 100644 --- a/llo/protocol/merkle_test.go +++ b/llo/protocol/merkle_test.go @@ -20,7 +20,6 @@ func testLeaves(n int) []*LLOMerkleLeafProto { llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr, - llotypes.ReportFormatEVMStreamlined, } leaves := make([]*LLOMerkleLeafProto, n) for i := range leaves { @@ -46,13 +45,13 @@ func Test_MerkleFamily(t *testing.T) { llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr, - llotypes.ReportFormatEVMStreamlined, } { family, ok := MerkleFamily(rf) assert.True(t, ok, rf.String()) assert.Equal(t, evmMerkle, family, rf.String()) } for _, rf := range []llotypes.ReportFormat{ + llotypes.ReportFormatEVMStreamlined, llotypes.ReportFormatJSON, llotypes.ReportFormatRetirement, llotypes.ReportFormatCapabilityTrigger, @@ -66,12 +65,14 @@ func Test_MerkleFamily(t *testing.T) { func Test_VerifySigningScheme(t *testing.T) { require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON})) - require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: llotypes.SigningSchemeMerkle})) + require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMPremiumLegacy, SigningScheme: llotypes.SigningSchemeMerkle})) + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: llotypes.SigningSchemeMerkle}), + `signing scheme "merkle" is not supported for report format evm_streamlined`) require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON, SigningScheme: llotypes.SigningSchemeMerkle}), `signing scheme "merkle" is not supported for report format json`) require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMMerkle}), `report format evm_merkle is a signing family, not a channel format`) - require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: "both"}), + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMPremiumLegacy, SigningScheme: "both"}), `unknown signing scheme "both"`) } @@ -109,7 +110,7 @@ func Test_MerkleLeafHash_DomainSeparation(t *testing.T) { assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "channel ID") other = proto.Clone(leaf).(*LLOMerkleLeafProto) - other.ReportFormat = uint32(llotypes.ReportFormatEVMStreamlined) + other.ReportFormat = uint32(llotypes.ReportFormatEVMABIEncodeUnpacked) assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "report format") assert.NotEqual(t, h, MerkleLeafHash(evmMerkle+1, leaf), "family") @@ -189,7 +190,7 @@ func Test_Merkle_GoldenVectors(t *testing.T) { {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, - {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{}}, {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, }, } @@ -201,10 +202,10 @@ func Test_Merkle_GoldenVectors(t *testing.T) { root, err := MerkleBundleRoot(bundle) require.NoError(t, err) - assert.Equal(t, "cee789eea2b2295270c2507936405a5dc9e3af1fcfc3c8c9cb605bae8e57b4e9", hex.EncodeToString(root[:])) + assert.Equal(t, "35096b66f71a326ee2afaddabd3aac3eb7aa0e585cd0d6efa8d5b904cddad81d", hex.EncodeToString(root[:])) msg := MerkleSigningMessage(digest, seqNr, evmMerkle, uint32(len(bundle.Leaves)), root) - assert.Equal(t, "82a749ca4b50caa0ea66a307bb3cffbc933bca6be71832179c775be8dee4ebac", hex.EncodeToString(msg[:])) + assert.Equal(t, "2745858e100b98d464dc9a0c031dbddd298b3ffca53d0af0bf8fd5dd867529ca", hex.EncodeToString(msg[:])) deliveries, err := ExpandMerkleBundle(bundle) require.NoError(t, err) @@ -215,13 +216,13 @@ func Test_Merkle_GoldenVectors(t *testing.T) { } } assert.Equal(t, [][]string{ - {"a9ca2f12f60482dba94c617c2c752d6f1770af1e796a3fe319e3a69bba71fc5a", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, - {"c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, - {"ae0b62b9ce280ffba7c5c0c1cad41c77928a9a408988e550d857e6ffe04dad22", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"a9ca2f12f60482dba94c617c2c752d6f1770af1e796a3fe319e3a69bba71fc5a", "c7d0680ae16ca7253972f33387a0a84bb662083739bc61c5cd04c83ce793b3e5", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", "c7d0680ae16ca7253972f33387a0a84bb662083739bc61c5cd04c83ce793b3e5", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"7c99b6d566a0caba97492cfbfef19f6fbbfc6f2198eec1cb3b27922472a93d90", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, {"4d1c23853ce24ad78df071013d6300555c3d36fa656a046b94c750b74661660a", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, // The last leaf is promoted twice, so its only sibling is the root of // the first four. - {"7e4ba02ae94d30d32ef66b329b325986ebadd188a13178fb2c0b9159268b9369"}, + {"6700579b32d25919b4a3b229eb3c443e9b37f76252ec10911cb135ec0ba64dd4"}, }, proofs) } @@ -300,9 +301,11 @@ func Test_MerkleDelivery(t *testing.T) { for name, f := range map[string]func(d *LLOMerkleDeliveryProto){ "report": func(d *LLOMerkleDeliveryProto) { d.Leaf.Report = append(d.Leaf.Report, 0) }, "channel": func(d *LLOMerkleDeliveryProto) { d.Leaf.ChannelID++ }, - "format": func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMPremiumLegacy) }, - "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, - "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, + "format": func(d *LLOMerkleDeliveryProto) { + d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMABIEncodeUnpacked) + }, + "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, + "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, // A changed leaf count can still reach the root. The signed message // binds it, see Test_MerkleProof_EveryLeaf. "leaf count": func(d *LLOMerkleDeliveryProto) { d.LeafCount = 9 }, @@ -366,7 +369,7 @@ func Test_SplitMerkleBundle(t *testing.T) { }) t.Run("oversized leaf is left out", func(t *testing.T) { - big := &LLOMerkleLeafProto{ChannelID: 99, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: make([]byte, 200)} + big := &LLOMerkleLeafProto{ChannelID: 99, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: make([]byte, 200)} input := []*LLOMerkleLeafProto{leaves[0], big, leaves[1]} bundles, oversized, err := SplitMerkleBundle(evmMerkle, input, 100) require.NoError(t, err) diff --git a/llo/reportcodec/evm/report_codec_evm_merkle_test.go b/llo/reportcodec/evm/report_codec_evm_merkle_test.go index 8fc90ad..f2e0df9 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle_test.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -28,7 +28,7 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, - {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{}}, {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, }, } diff --git a/llo/transmitter/dataengine/orm.go b/llo/transmitter/dataengine/orm.go index 0e461f2..a010f1b 100644 --- a/llo/transmitter/dataengine/orm.go +++ b/llo/transmitter/dataengine/orm.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "math" + "slices" "time" "github.com/lib/pq" @@ -30,6 +31,10 @@ type orm struct { donID uint32 } +// insertBatchRows bounds the rows of one INSERT. Each row binds 10 parameters +// and Postgres accepts at most 65535 in one statement. +const insertBatchRows = 5000 + func NewORM(ds sqlutil.DataSource, donID uint32) ORM { return &orm{ds, donID} } @@ -83,14 +88,15 @@ func (o *orm) Insert(ctx context.Context, transmissions []*Transmission) error { } } - _, err := o.ds.NamedExecContext(ctx, ` + for batch := range slices.Chunk(records, insertBatchRows) { + _, err := o.ds.NamedExecContext(ctx, ` INSERT INTO llo_mercury_transmit_queue (don_id, server_url, config_digest, seq_nr, report, lifecycle_stage, report_format, signatures, signers, transmission_hash) VALUES (:don_id, :server_url, :config_digest, :seq_nr, :report, :lifecycle_stage, :report_format, :signatures, :signers, :transmission_hash) ON CONFLICT (transmission_hash) DO NOTHING - `, records) - - if err != nil { - return fmt.Errorf("llo orm: failed to insert transmissions: %w", err) + `, batch) + if err != nil { + return fmt.Errorf("llo orm: failed to insert transmissions: %w", err) + } } return nil } diff --git a/llo/transmitter/dataengine/orm_test.go b/llo/transmitter/dataengine/orm_test.go index e1e70ce..05800c3 100644 --- a/llo/transmitter/dataengine/orm_test.go +++ b/llo/transmitter/dataengine/orm_test.go @@ -145,6 +145,24 @@ func TestORM(t *testing.T) { require.NoError(t, err) require.Len(t, result, 5) }) + + t.Run("Insert splits rows beyond the bind parameter limit", func(t *testing.T) { + donID := uint32(102) + orm := NewORM(db, donID) + + // 10 parameters per row, so this exceeds the 65535 Postgres allows in + // one statement. + const n = 7000 + // A server URL of its own keeps the transmission hashes apart from + // the rows other subtests insert. + serverURL := "wss://mercuryserver.test/insert-batches" + transmissions := makeSampleTransmissions(n, serverURL) + require.NoError(t, orm.Insert(ctx, transmissions)) + + result, err := orm.Get(ctx, serverURL, n+1, 0) + require.NoError(t, err) + require.Len(t, result, n) + }) } // TestORM_PruneSkipsRowsLockedByDelete checks that Prune does not wait for rows that a concurrent Delete has diff --git a/llo/transmitter/dataengine/server_merkle_test.go b/llo/transmitter/dataengine/server_merkle_test.go index c3ef2a6..1c2f90b 100644 --- a/llo/transmitter/dataengine/server_merkle_test.go +++ b/llo/transmitter/dataengine/server_merkle_test.go @@ -32,7 +32,7 @@ func Test_server_transmit_EVMMerkle(t *testing.T) { Family: uint32(llotypes.ReportFormatEVMMerkle), Leaves: []*protocol.LLOMerkleLeafProto{ {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, - {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte("two")}, }, } deliveries, err := protocol.ExpandMerkleBundle(bundle) diff --git a/llo/transmitter/dataengine/transmitter.go b/llo/transmitter/dataengine/transmitter.go index 8a9be08..c9b9ca1 100644 --- a/llo/transmitter/dataengine/transmitter.go +++ b/llo/transmitter/dataengine/transmitter.go @@ -124,8 +124,8 @@ type transmitter struct { stopCh services.StopChan wg *sync.WaitGroup - // commitCh carries transmissions to the commit loops, one per send for - // Transmit and a whole batch per send for TransmitBatch. + // commitCh carries the transmissions of one Transmit or TransmitBatch + // call, for every server, per send. commitCh chan []*Transmission } @@ -254,29 +254,8 @@ func (mt *transmitter) Transmit( seqNr uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature, -) (err error) { - ok := mt.IfStarted(func() { - for serverURL := range mt.servers { - t := &Transmission{ - ServerURL: serverURL, - ConfigDigest: digest, - SeqNr: seqNr, - Report: report, - Sigs: sigs, - } - select { - case mt.commitCh <- []*Transmission{t}: - case <-ctx.Done(): - err = fmt.Errorf("failed to add transmission to commit channel: %w", ctx.Err()) - } - } - }) - - if !ok { - return errors.New("transmitter is not started") - } - - return err +) error { + return mt.TransmitBatch(ctx, digest, seqNr, []ocr3types.ReportWithInfo[llotypes.ReportInfo]{report}, sigs) } // TransmitBatch enqueues reports that share a digest, seqNr and signatures, diff --git a/llo/transmitter/transmitter_merkle_test.go b/llo/transmitter/transmitter_merkle_test.go index b6ef448..87fdf9f 100644 --- a/llo/transmitter/transmitter_merkle_test.go +++ b/llo/transmitter/transmitter_merkle_test.go @@ -78,7 +78,7 @@ func Test_transmitter_ExpandsMerkleBundle(t *testing.T) { Family: uint32(llotypes.ReportFormatEVMMerkle), Leaves: []*protocol.LLOMerkleLeafProto{ {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, - {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte("two")}, {ChannelID: 5, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte("five")}, }, } diff --git a/llo/v30/plugin_observation.go b/llo/v30/plugin_observation.go index 7b56bfe..d92b2d2 100644 --- a/llo/v30/plugin_observation.go +++ b/llo/v30/plugin_observation.go @@ -81,7 +81,7 @@ func (p *Plugin) observation(ctx context.Context, outctx ocr3types.OutcomeContex // ChannelIDs should always be sorted the same way (channel ID ascending). expectedChannelDefs, unsupported := withoutSigningSchemes(previousOutcome.ChannelDefinitions, p.ChannelDefinitionCache.Definitions(previousOutcome.ChannelDefinitions)) if len(unsupported) > 0 { - p.Logger.Errorw("ChannelDefinitionCache.Definitions has channels with a signing scheme, which LLO v30 does not support, not voting for them", "channelIDs", unsupported) + p.Logger.Errorw("ChannelDefinitionCache.Definitions has channels with a signing scheme, which LLO v30 does not support, or backfilling one, not voting for them", "channelIDs", unsupported) } // Only the channels this node would vote to add or change are held // to the admission-only checks; the ones already committed are not, @@ -225,14 +225,13 @@ func sortChannelIDs(cids []llotypes.ChannelID) { // SigningScheme reverted to its committed definition, or left out if it has // none, and the reverted channel IDs in ascending order. v30 signs every report // on its own, so it never votes for such a channel, which a channel -// definitions cache shared with a v31 instance can hold. +// definitions cache shared with a v31 instance can hold. A history_backfill +// channel that targets a reverted channel is reverted with it, or admission +// would fail for the whole set on a target v30 leaves out. func withoutSigningSchemes(committed, expected llotypes.ChannelDefinitions) (llotypes.ChannelDefinitions, []llotypes.ChannelID) { var out llotypes.ChannelDefinitions var unsupported []llotypes.ChannelID - for channelID, cd := range expected { - if cd.SigningScheme == llotypes.SigningSchemeDefault { - continue - } + revert := func(channelID llotypes.ChannelID) { if out == nil { // expected may share its backing map with the previous outcome. out = maps.Clone(expected) @@ -244,9 +243,32 @@ func withoutSigningSchemes(committed, expected llotypes.ChannelDefinitions) (llo } unsupported = append(unsupported, channelID) } + for channelID, cd := range expected { + if cd.SigningScheme != llotypes.SigningSchemeDefault { + revert(channelID) + } + } if out == nil { return expected, nil } + reverted := make(map[llotypes.ChannelID]struct{}, len(unsupported)) + for _, channelID := range unsupported { + reverted[channelID] = struct{}{} + } + // A backfill channel never targets another backfill channel, so one pass + // reaches every dependent. + for channelID, cd := range expected { + if _, ok := reverted[channelID]; ok || cd.ReportFormat != llotypes.ReportFormatHistoryBackfill { + continue + } + opts, err := protocol.ParseHistoryBackfillOpts(cd.Opts) + if err != nil { + continue + } + if _, ok := reverted[opts.TargetChannelID]; ok { + revert(channelID) + } + } sort.Slice(unsupported, func(i, j int) bool { return unsupported[i] < unsupported[j] }) return out, unsupported } diff --git a/llo/v30/plugin_test.go b/llo/v30/plugin_test.go index 69bfb22..b106164 100644 --- a/llo/v30/plugin_test.go +++ b/llo/v30/plugin_test.go @@ -2,6 +2,7 @@ package llo import ( "context" + "fmt" "testing" "github.com/shopspring/decimal" @@ -174,4 +175,22 @@ func Test_withoutSigningSchemes(t *testing.T) { assert.Equal(t, llotypes.ChannelDefinitions{1: plain, 2: plain}, got) assert.Equal(t, []llotypes.ChannelID{2, 3}, unsupported) assert.Equal(t, merkle, expected[2], "the input must not be modified") + + // A backfill channel follows a target that is reverted or left out. + backfill := func(target llotypes.ChannelID) llotypes.ChannelDefinition { + return llotypes.ChannelDefinition{ + ReportFormat: llotypes.ReportFormatHistoryBackfill, + Opts: llotypes.ChannelOpts(fmt.Sprintf(`{"targetChannelId":%d,"observations":{"1":{"1":"1"}}}`, target)), + } + } + committed = llotypes.ChannelDefinitions{1: plain, 2: plain, 4: backfill(2)} + expected = llotypes.ChannelDefinitions{1: plain, 2: merkle, 3: merkle, 4: backfill(1), 5: backfill(3), 6: backfill(1)} + got, unsupported = withoutSigningSchemes(committed, expected) + assert.Equal(t, llotypes.ChannelDefinitions{1: plain, 2: plain, 4: backfill(1), 6: backfill(1)}, got) + assert.Equal(t, []llotypes.ChannelID{2, 3, 5}, unsupported) + + expected = llotypes.ChannelDefinitions{1: plain, 2: merkle, 4: backfill(2)} + got, unsupported = withoutSigningSchemes(committed, expected) + assert.Equal(t, committed, got) + assert.Equal(t, []llotypes.ChannelID{2, 4}, unsupported) } From defbe0b35c12c27b5562bc662d6d7552c36e3093 Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Thu, 5 Nov 2026 12:24:52 +0000 Subject: [PATCH 4/9] llo: add EVMStreamlined to the EVM Merkle family Add EVMStreamlined as a member of the EVM Merkle family. The verifier proxy, verifier and fee manager read the feed ID from the first 32 bytes of the report, so reject signingScheme merkle on a streamlined channel without one. Leave the feed ID version unchecked, since NoOpFeeManager ignores the payload. Restore the streamlined leaves and original golden vectors in the Merkle tests. --- llo/dev/v31/doc.go | 7 ++-- llo/dev/v31/merkle_test.go | 6 ++-- llo/protocol/merkle.go | 11 +++--- llo/protocol/merkle_test.go | 35 +++++++++---------- llo/reportcodec/evm/encodable_test.go | 16 +++++++++ .../evm/report_codec_evm_merkle.go | 4 +++ .../evm/report_codec_evm_merkle_test.go | 2 +- .../evm/report_codec_evm_streamlined.go | 8 ++++- .../dataengine/server_merkle_test.go | 2 +- llo/transmitter/transmitter_merkle_test.go | 2 +- 10 files changed, 58 insertions(+), 35 deletions(-) diff --git a/llo/dev/v31/doc.go b/llo/dev/v31/doc.go index 50522b4..2b097d8 100644 --- a/llo/dev/v31/doc.go +++ b/llo/dev/v31/doc.go @@ -209,10 +209,9 @@ // delivery per channel with its proof. See protocol/merkle.go for the tree and // the signed message. // -// The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers the -// formats in llo/reportcodec/evm whose reports start with the feed ID, so every -// one but EVMStreamlined. Backfill reports follow the scheme of their target -// channel. +// The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers every +// format in llo/reportcodec/evm. An EVMStreamlined channel needs a feed ID to +// join. Backfill reports follow the scheme of their target channel. // // A family is not tied to a destination chain. It fixes one signing key, one // hash and signature scheme, and one delivery packer. The root is signed once diff --git a/llo/dev/v31/merkle_test.go b/llo/dev/v31/merkle_test.go index 13eecef..e85f2ac 100644 --- a/llo/dev/v31/merkle_test.go +++ b/llo/dev/v31/merkle_test.go @@ -89,7 +89,7 @@ func Test_Reports_MerkleBundle(t *testing.T) { defs := llotypes.ChannelDefinitions{ 1: merkleChannel(llotypes.ReportFormatJSON, llotypes.SigningSchemeDefault), 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), - 3: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), 4: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeDefault), 5: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), } @@ -112,7 +112,7 @@ func Test_Reports_MerkleBundle(t *testing.T) { format llotypes.ReportFormat }{ {2, llotypes.ReportFormatEVMABIEncodeUnpacked}, - {3, llotypes.ReportFormatEVMPremiumLegacy}, + {3, llotypes.ReportFormatEVMStreamlined}, {5, llotypes.ReportFormatEVMPremiumLegacy}, } { leaf := bundle.Leaves[i] @@ -153,7 +153,7 @@ func Test_Reports_MerkleBundleSplitsBySize(t *testing.T) { defs := llotypes.ChannelDefinitions{ 1: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), 2: merkleChannel(llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.SigningSchemeMerkle), - 3: merkleChannel(llotypes.ReportFormatEVMPremiumLegacy, llotypes.SigningSchemeMerkle), + 3: merkleChannel(llotypes.ReportFormatEVMStreamlined, llotypes.SigningSchemeMerkle), } rwis, err := p.Reports(t.Context(), 3, merklePrecursor(t, protocol.LifeCycleStageProduction, defs)) require.NoError(t, err) diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go index adff0f0..98a4a48 100644 --- a/llo/protocol/merkle.go +++ b/llo/protocol/merkle.go @@ -48,15 +48,16 @@ type MerkleHash = [32]byte // MerkleFamily returns the signing family that channels in format join under // SigningSchemeMerkle, and false if format has none. // -// The EVM family covers the formats in llo/reportcodec/evm whose reports start -// with the feed ID, as the fee manager reads them. They all hash with -// keccak256, so one bundle can hold all of them. EVMStreamlined reports are -// packed without that header and stay out. +// The EVM family covers every format with a codec in llo/reportcodec/evm. They +// all produce reports for EVM verifiers and hash with keccak256, so one bundle +// can hold all of them. An EVMStreamlined channel joins only with a feed ID, so +// its reports start with one like the others (see ReportCodecEVMStreamlined). func MerkleFamily(format llotypes.ReportFormat) (llotypes.ReportFormat, bool) { switch format { case llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, - llotypes.ReportFormatEVMABIEncodeUnpackedExpr: + llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined: return llotypes.ReportFormatEVMMerkle, true default: return 0, false diff --git a/llo/protocol/merkle_test.go b/llo/protocol/merkle_test.go index 46dc5b5..4648ca7 100644 --- a/llo/protocol/merkle_test.go +++ b/llo/protocol/merkle_test.go @@ -20,6 +20,7 @@ func testLeaves(n int) []*LLOMerkleLeafProto { llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined, } leaves := make([]*LLOMerkleLeafProto, n) for i := range leaves { @@ -45,13 +46,13 @@ func Test_MerkleFamily(t *testing.T) { llotypes.ReportFormatEVMPremiumLegacy, llotypes.ReportFormatEVMABIEncodeUnpacked, llotypes.ReportFormatEVMABIEncodeUnpackedExpr, + llotypes.ReportFormatEVMStreamlined, } { family, ok := MerkleFamily(rf) assert.True(t, ok, rf.String()) assert.Equal(t, evmMerkle, family, rf.String()) } for _, rf := range []llotypes.ReportFormat{ - llotypes.ReportFormatEVMStreamlined, llotypes.ReportFormatJSON, llotypes.ReportFormatRetirement, llotypes.ReportFormatCapabilityTrigger, @@ -65,14 +66,12 @@ func Test_MerkleFamily(t *testing.T) { func Test_VerifySigningScheme(t *testing.T) { require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON})) - require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMPremiumLegacy, SigningScheme: llotypes.SigningSchemeMerkle})) - require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: llotypes.SigningSchemeMerkle}), - `signing scheme "merkle" is not supported for report format evm_streamlined`) + require.NoError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: llotypes.SigningSchemeMerkle})) require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatJSON, SigningScheme: llotypes.SigningSchemeMerkle}), `signing scheme "merkle" is not supported for report format json`) require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMMerkle}), `report format evm_merkle is a signing family, not a channel format`) - require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMPremiumLegacy, SigningScheme: "both"}), + require.EqualError(t, VerifySigningScheme(llotypes.ChannelDefinition{ReportFormat: llotypes.ReportFormatEVMStreamlined, SigningScheme: "both"}), `unknown signing scheme "both"`) } @@ -110,7 +109,7 @@ func Test_MerkleLeafHash_DomainSeparation(t *testing.T) { assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "channel ID") other = proto.Clone(leaf).(*LLOMerkleLeafProto) - other.ReportFormat = uint32(llotypes.ReportFormatEVMABIEncodeUnpacked) + other.ReportFormat = uint32(llotypes.ReportFormatEVMStreamlined) assert.NotEqual(t, h, MerkleLeafHash(evmMerkle, other), "report format") assert.NotEqual(t, h, MerkleLeafHash(evmMerkle+1, leaf), "family") @@ -190,7 +189,7 @@ func Test_Merkle_GoldenVectors(t *testing.T) { {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, - {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, }, } @@ -202,10 +201,10 @@ func Test_Merkle_GoldenVectors(t *testing.T) { root, err := MerkleBundleRoot(bundle) require.NoError(t, err) - assert.Equal(t, "35096b66f71a326ee2afaddabd3aac3eb7aa0e585cd0d6efa8d5b904cddad81d", hex.EncodeToString(root[:])) + assert.Equal(t, "cee789eea2b2295270c2507936405a5dc9e3af1fcfc3c8c9cb605bae8e57b4e9", hex.EncodeToString(root[:])) msg := MerkleSigningMessage(digest, seqNr, evmMerkle, uint32(len(bundle.Leaves)), root) - assert.Equal(t, "2745858e100b98d464dc9a0c031dbddd298b3ffca53d0af0bf8fd5dd867529ca", hex.EncodeToString(msg[:])) + assert.Equal(t, "82a749ca4b50caa0ea66a307bb3cffbc933bca6be71832179c775be8dee4ebac", hex.EncodeToString(msg[:])) deliveries, err := ExpandMerkleBundle(bundle) require.NoError(t, err) @@ -216,13 +215,13 @@ func Test_Merkle_GoldenVectors(t *testing.T) { } } assert.Equal(t, [][]string{ - {"a9ca2f12f60482dba94c617c2c752d6f1770af1e796a3fe319e3a69bba71fc5a", "c7d0680ae16ca7253972f33387a0a84bb662083739bc61c5cd04c83ce793b3e5", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, - {"c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", "c7d0680ae16ca7253972f33387a0a84bb662083739bc61c5cd04c83ce793b3e5", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, - {"7c99b6d566a0caba97492cfbfef19f6fbbfc6f2198eec1cb3b27922472a93d90", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"a9ca2f12f60482dba94c617c2c752d6f1770af1e796a3fe319e3a69bba71fc5a", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"c77f76bdb77a1e6a7145ea23d2f9309047f3020187de3013c01cee82bff6f057", "ba2504762e114a693f259e800f8e66387fb59e0a217d6caa40e6f5e54703ada2", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, + {"ae0b62b9ce280ffba7c5c0c1cad41c77928a9a408988e550d857e6ffe04dad22", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, {"4d1c23853ce24ad78df071013d6300555c3d36fa656a046b94c750b74661660a", "b31bd790ac0b0f71e3db167a3d275efab380d4fbcaca3ec7646958b8f6e0bf19", "cb05384430fa7e800cea5134251e599c40b4f2b52a46a5bccc70a21f69483a0b"}, // The last leaf is promoted twice, so its only sibling is the root of // the first four. - {"6700579b32d25919b4a3b229eb3c443e9b37f76252ec10911cb135ec0ba64dd4"}, + {"7e4ba02ae94d30d32ef66b329b325986ebadd188a13178fb2c0b9159268b9369"}, }, proofs) } @@ -301,11 +300,9 @@ func Test_MerkleDelivery(t *testing.T) { for name, f := range map[string]func(d *LLOMerkleDeliveryProto){ "report": func(d *LLOMerkleDeliveryProto) { d.Leaf.Report = append(d.Leaf.Report, 0) }, "channel": func(d *LLOMerkleDeliveryProto) { d.Leaf.ChannelID++ }, - "format": func(d *LLOMerkleDeliveryProto) { - d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMABIEncodeUnpacked) - }, - "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, - "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, + "format": func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMPremiumLegacy) }, + "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, + "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, // A changed leaf count can still reach the root. The signed message // binds it, see Test_MerkleProof_EveryLeaf. "leaf count": func(d *LLOMerkleDeliveryProto) { d.LeafCount = 9 }, @@ -369,7 +366,7 @@ func Test_SplitMerkleBundle(t *testing.T) { }) t.Run("oversized leaf is left out", func(t *testing.T) { - big := &LLOMerkleLeafProto{ChannelID: 99, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: make([]byte, 200)} + big := &LLOMerkleLeafProto{ChannelID: 99, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: make([]byte, 200)} input := []*LLOMerkleLeafProto{leaves[0], big, leaves[1]} bundles, oversized, err := SplitMerkleBundle(evmMerkle, input, 100) require.NoError(t, err) diff --git a/llo/reportcodec/evm/encodable_test.go b/llo/reportcodec/evm/encodable_test.go index 484563f..4bfd59f 100644 --- a/llo/reportcodec/evm/encodable_test.go +++ b/llo/reportcodec/evm/encodable_test.go @@ -163,6 +163,22 @@ func TestVerifyForAdmission(t *testing.T) { } } +func TestVerifyForAdmission_StreamlinedMerkleNeedsFeedID(t *testing.T) { + codec := NewReportCodecStreamlined(logger.Nop()) + cd := llotypes.ChannelDefinition{ + Opts: []byte(`{"abi":[{"type":"int192"}]}`), + SigningScheme: llotypes.SigningSchemeMerkle, + } + require.EqualError(t, codec.VerifyForAdmission(cd), `signing scheme "merkle" requires a feed ID`) + + cd.Opts = []byte(`{"feedID":` + testFeedID + `,"abi":[{"type":"int192"}]}`) + require.NoError(t, codec.VerifyForAdmission(cd)) + + cd.Opts = []byte(`{"abi":[{"type":"int192"}]}`) + cd.SigningScheme = llotypes.SigningSchemeDefault + require.NoError(t, codec.VerifyForAdmission(cd)) +} + // streamlinedOpts returns opts with n uint256 elements. Without a feed ID the // header is 16 bytes, so 2047 elements make 65520 bytes and 2048 make 65552. func streamlinedOpts(n int, feedID bool) string { diff --git a/llo/reportcodec/evm/report_codec_evm_merkle.go b/llo/reportcodec/evm/report_codec_evm_merkle.go index acd790c..2191416 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle.go @@ -18,6 +18,10 @@ import ( // verifier proxy routes it by reportContext[0], the config digest, and the fee // manager reads the report from it unchanged. The Merkle fields follow. // +// An EVMStreamlined leaf starts with its feed ID but carries no fee fields. A +// fee manager that decodes fees from the report, unlike NoOpFeeManager, must +// skip it. +// // reportContext[1] holds MerkleReportContextTag in its first bytes and seqNr in // its last 8. A legacy report context has 27 zero bytes there, so a verifier // tells the two payloads apart by the tag. reportContext[2] is zero. diff --git a/llo/reportcodec/evm/report_codec_evm_merkle_test.go b/llo/reportcodec/evm/report_codec_evm_merkle_test.go index f2e0df9..8fc90ad 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle_test.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -28,7 +28,7 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{0x01}}, {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte{0x02, 0x02}}, {ChannelID: 7, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte{0x07}}, - {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte{}}, + {ChannelID: 9, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte{}}, {ChannelID: 10, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("ten")}, }, } diff --git a/llo/reportcodec/evm/report_codec_evm_streamlined.go b/llo/reportcodec/evm/report_codec_evm_streamlined.go index ca060b8..639a670 100644 --- a/llo/reportcodec/evm/report_codec_evm_streamlined.go +++ b/llo/reportcodec/evm/report_codec_evm_streamlined.go @@ -104,7 +104,10 @@ func (rc ReportCodecEVMStreamlined) Verify(cd llotypes.ChannelDefinition) error // VerifyForAdmission implements protocol.AdmissionVerifier: it rejects ABI // types the packed encoder cannot encode, and an ABI whose largest report // exceeds the uint16 length prefix Pack writes. Both fail every report of the -// channel, the second only after it was signed. +// channel, the second only after it was signed. It also rejects +// SigningSchemeMerkle without a feed ID: a Merkle delivery goes through the +// EVM verifier proxy, where the fee manager and the verifier read the feed ID +// from the first 32 bytes of the report. // // This is not part of Verify because definitions committed before the check // existed may fail it, and rejecting those would stop every oracle from @@ -117,6 +120,9 @@ func (rc ReportCodecEVMStreamlined) VerifyForAdmission(cd llotypes.ChannelDefini if err := verifyABITypes(opts.ABI, true); err != nil { return err } + if cd.SigningScheme == llotypes.SigningSchemeMerkle && opts.FeedID == nil { + return fmt.Errorf("signing scheme %q requires a feed ID", cd.SigningScheme) + } // Feed ID or report format and channel ID, then validAfter. size := 4 + 4 + 8 if opts.FeedID != nil { diff --git a/llo/transmitter/dataengine/server_merkle_test.go b/llo/transmitter/dataengine/server_merkle_test.go index 1c2f90b..c3ef2a6 100644 --- a/llo/transmitter/dataengine/server_merkle_test.go +++ b/llo/transmitter/dataengine/server_merkle_test.go @@ -32,7 +32,7 @@ func Test_server_transmit_EVMMerkle(t *testing.T) { Family: uint32(llotypes.ReportFormatEVMMerkle), Leaves: []*protocol.LLOMerkleLeafProto{ {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, - {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte("two")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, }, } deliveries, err := protocol.ExpandMerkleBundle(bundle) diff --git a/llo/transmitter/transmitter_merkle_test.go b/llo/transmitter/transmitter_merkle_test.go index 87fdf9f..b6ef448 100644 --- a/llo/transmitter/transmitter_merkle_test.go +++ b/llo/transmitter/transmitter_merkle_test.go @@ -78,7 +78,7 @@ func Test_transmitter_ExpandsMerkleBundle(t *testing.T) { Family: uint32(llotypes.ReportFormatEVMMerkle), Leaves: []*protocol.LLOMerkleLeafProto{ {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpacked), Report: []byte("one")}, - {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMABIEncodeUnpackedExpr), Report: []byte("two")}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, {ChannelID: 5, ReportFormat: uint32(llotypes.ReportFormatEVMPremiumLegacy), Report: []byte("five")}, }, } From a6fff4a7a08a20472b3086afb7bf3995caac31aa Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Thu, 5 Nov 2026 12:49:20 +0000 Subject: [PATCH 5/9] llo/reportcodec/evm: pin the Merkle delivery payload byte layout Check the ABI payload ReportCodecEVMMerkle packs, slot by slot, head offsets, the tag and seqNr in the report context, the v bytes in rawVs, the report, signature and proof sections, and the total length. --- .../evm/report_codec_evm_merkle_test.go | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/llo/reportcodec/evm/report_codec_evm_merkle_test.go b/llo/reportcodec/evm/report_codec_evm_merkle_test.go index 8fc90ad..e0d3453 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle_test.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -122,6 +122,56 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { } }) + // The byte layout is the spec the onchain verifier is written against. + t.Run("byte layout", func(t *testing.T) { + d := deliveries[1] + report, err := protocol.EncodeMerkleDelivery(d) + require.NoError(t, err) + payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) + require.NoError(t, err) + + word := func(offset int) []byte { return payload[offset : offset+32] } + uint64At := func(offset int) uint64 { return binary.BigEndian.Uint64(word(offset)[24:]) } + + n, p, l := len(sigs), len(d.Proof), len(d.Leaf.Report) + reportOffset := 384 + rsOffset := reportOffset + 32 + (l+31)/32*32 + ssOffset := rsOffset + 32 + 32*n + proofOffset := ssOffset + 32 + 32*n + require.Len(t, payload, proofOffset+32+32*p) + + assert.Equal(t, digest[:], word(0)) + assert.Equal(t, []byte(MerkleReportContextTag), word(32)[:len(MerkleReportContextTag)]) + assert.Equal(t, make([]byte, 24-len(MerkleReportContextTag)), word(32)[len(MerkleReportContextTag):24]) + assert.Equal(t, seqNr, uint64At(32)) + assert.Equal(t, make([]byte, 32), word(64)) + assert.Equal(t, uint64(reportOffset), uint64At(96)) + assert.Equal(t, uint64(rsOffset), uint64At(128)) + assert.Equal(t, uint64(ssOffset), uint64At(160)) + for i, sig := range sigs { + assert.Equal(t, sig.Signature[64], word(192)[i]) + } + assert.Equal(t, make([]byte, 32-n), word(192)[n:]) + assert.Equal(t, uint64(d.LeafCount), uint64At(224)) + assert.Equal(t, uint64(d.LeafIndex), uint64At(256)) + assert.Equal(t, uint64(d.Leaf.ChannelID), uint64At(288)) + assert.Equal(t, uint64(d.Leaf.ReportFormat), uint64At(320)) + assert.Equal(t, uint64(proofOffset), uint64At(352)) + + assert.Equal(t, uint64(l), uint64At(reportOffset)) + assert.Equal(t, d.Leaf.Report, payload[reportOffset+32:reportOffset+32+l]) + assert.Equal(t, uint64(n), uint64At(rsOffset)) + assert.Equal(t, uint64(n), uint64At(ssOffset)) + for i, sig := range sigs { + assert.Equal(t, sig.Signature[:32], word(rsOffset+32+32*i)) + assert.Equal(t, sig.Signature[32:64], word(ssOffset+32+32*i)) + } + assert.Equal(t, uint64(p), uint64At(proofOffset)) + for i, h := range d.Proof { + assert.Equal(t, h, word(proofOffset+32+32*i)) + } + }) + t.Run("rejects an invalid delivery", func(t *testing.T) { _, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, []byte{0xff}, sigs) require.Error(t, err) From 2785b7d2a87de5fe4809b2879855ddc539289d35 Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Thu, 5 Nov 2026 18:57:06 +0000 Subject: [PATCH 6/9] temp bump of chainlink-common --- go.mod | 8 ++++---- go.sum | 6 ++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index d4e390d..3525d73 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/smartcontractkit/chainlink-data-streams -go 1.27.1 +go 1.27.3 require ( github.com/cespare/xxhash/v2 v2.3.0 @@ -20,7 +20,7 @@ require ( github.com/prometheus/client_golang v1.23.2 github.com/prometheus/client_model v0.6.2 github.com/shopspring/decimal v1.4.0 - github.com/smartcontractkit/chainlink-common v0.11.2-0.20260918171610-2b348aaadc86 + github.com/smartcontractkit/chainlink-common v0.11.2-0.20261105185100-6359ed4cf932 github.com/smartcontractkit/chainlink-common/keystore v1.1.0 github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20260512150409-b4068bf735e6 github.com/smartcontractkit/libocr v0.0.0-20260810200708-618b5bf7f342 @@ -147,8 +147,8 @@ require ( github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/sigurn/crc16 v0.0.0-20211026045750-20ab5afb07e3 // indirect github.com/smartcontractkit/chain-selectors v1.0.104 // indirect - github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20260915184316-2730f1867c92 // indirect - github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20260804191526-b7a850ae7648 // indirect + github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 // indirect + github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b // indirect github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 // indirect github.com/smartcontractkit/chainlink-protos/metering/go v0.0.0-20260710151514-27b5a126dabe // indirect github.com/smartcontractkit/chainlink-protos/node-platform v0.0.0-20260709145319-7782fb89eb16 // indirect diff --git a/go.sum b/go.sum index 97147a8..4a76d13 100644 --- a/go.sum +++ b/go.sum @@ -552,14 +552,20 @@ github.com/smartcontractkit/chain-selectors v1.0.104 h1:/n9pPGM5W/+r1eHoWZv4VwX9 github.com/smartcontractkit/chain-selectors v1.0.104/go.mod h1:qy7whtgG5g+7z0jt0nRyii9bLND9m15NZTzuQPkMZ5w= github.com/smartcontractkit/chainlink-common v0.11.2-0.20260918171610-2b348aaadc86 h1:Ncg9P2qAjLTia4gc3QpqhaHL+kNX2dPxJxS4O8jRgbA= github.com/smartcontractkit/chainlink-common v0.11.2-0.20260918171610-2b348aaadc86/go.mod h1:BniOJQOh52lgDDNyfOQJEmQUVQ68txTSeT0Qxwt0zQI= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261105185100-6359ed4cf932 h1:zH6F01xyIFMaGKBx2FNrrWuN0JY9wgNz5xz295lAu8s= +github.com/smartcontractkit/chainlink-common v0.11.2-0.20261105185100-6359ed4cf932/go.mod h1:GQPosLRkCllnWENEHTetu6W5/xuFC24QMqXm35mYmt4= github.com/smartcontractkit/chainlink-common/keystore v1.1.0 h1:2wzySccgk2fpWusPKO0bpeAZzfSU9eq6CS5U+JwYaVo= github.com/smartcontractkit/chainlink-common/keystore v1.1.0/go.mod h1:6JexOOhPhknQ0QMuppFIlOpm6wCp54yZMxai+tWugwY= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20260915184316-2730f1867c92 h1:Z1OIGukDhJD+Gknr5G07Vtml24E7BwKaIQoWzV/SdqA= github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20260915184316-2730f1867c92/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549 h1:J4vYRJxkBO8Yf//17wScKjYWmS45VZaFWx0zt+4ETEU= +github.com/smartcontractkit/chainlink-common/pkg/chipingress v0.0.11-0.20261005132539-b7d63d5fd549/go.mod h1:Scyk7O80fde5rJF3Ty3fEE3xiS6j84eWbu8/2gl3pIY= github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20260512150409-b4068bf735e6 h1:JFo7C3FilwhfwGBLAyj2umbL+P4QxGmVi/b8yt9kqvI= github.com/smartcontractkit/chainlink-evm/gethwrappers v0.0.0-20260512150409-b4068bf735e6/go.mod h1:a260YnLyWq2NHLUN5cSVyMGk9nhO6RguCaTI2rsVqyA= github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20260804191526-b7a850ae7648 h1:WEUMkKQPAgcNMRgES6CBWrRUiII+HKEWQjulKQBSuMA= github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20260804191526-b7a850ae7648/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b h1:tlxPkVQ6ZpJIElqUWc4lU5VH4BB6OzhckG/gHwpaaa0= +github.com/smartcontractkit/chainlink-protos/cre/go v0.0.0-20261013212015-e622e8b83b6b/go.mod h1:/i8hjTPFdVWHiY+QjeSiVS2Z3GB3WAZznGgXHstC02E= github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305 h1:NJdGFhzT6zMaTod4QkBqVD2sg0I25iw1boOYtTpEwRo= github.com/smartcontractkit/chainlink-protos/linking-service/go v0.0.0-20260512230622-65f10f4cd305/go.mod h1:qSTSwX3cBP3FKQwQacdjArqv0g6QnukjV4XuzO6UyoY= github.com/smartcontractkit/chainlink-protos/metering/go v0.0.0-20260710151514-27b5a126dabe h1:MDnY5wQbWTpFdDnMRicEnoMfSP5nM/KncARr4skP1ug= From 938950508543d62767501dc60f8fb4c57f41fc2d Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Mon, 9 Nov 2026 15:52:35 +0000 Subject: [PATCH 7/9] llo/dev/v31: share the Merkle bundle tree between signing and transmit Add protocol.LoadMerkleBundle, a shared cache of 32 trees keyed by the sha256 of the encoded bundle. The keyring takes the signing root from it and the transmitter expands deliveries from the same tree, so each node builds the tree once per bundle instead of twice. The cache keeps the tree, root, family and leaf count, not the decoded leaves. MerkleBundle.Expand decodes the bundle again and rejects bytes that do not match the loaded tree. A miss after eviction rebuilds the tree, so the result is unchanged. --- llo/keyring/keyring.go | 76 +++--------------------- llo/keyring/keyring_test.go | 20 ------- llo/protocol/merkle.go | 6 +- llo/protocol/merkle_cache.go | 98 +++++++++++++++++++++++++++++++ llo/protocol/merkle_cache_test.go | 75 +++++++++++++++++++++++ llo/transmitter/transmitter.go | 8 +-- 6 files changed, 190 insertions(+), 93 deletions(-) create mode 100644 llo/protocol/merkle_cache.go create mode 100644 llo/protocol/merkle_cache_test.go diff --git a/llo/keyring/keyring.go b/llo/keyring/keyring.go index 51ad6b4..bd943f2 100644 --- a/llo/keyring/keyring.go +++ b/llo/keyring/keyring.go @@ -4,12 +4,10 @@ package keyring import ( "bytes" - "crypto/sha256" "fmt" "maps" "slices" "sort" - "sync" "github.com/ethereum/go-ethereum/crypto" @@ -41,15 +39,14 @@ type Key interface { } type onchainKeyring struct { - lggr logger.Logger - keys map[llotypes.ReportFormat]Key - donID uint32 - merkleRoots *merkleRootCache + lggr logger.Logger + keys map[llotypes.ReportFormat]Key + donID uint32 } func NewOnchainKeyring(lggr logger.Logger, keys map[llotypes.ReportFormat]Key, donID uint32) OnchainKeyring { return &onchainKeyring{ - logger.Sugared(lggr).Named("OnchainKeyring"), keys, donID, newMerkleRootCache(merkleRootCacheSize), + logger.Sugared(lggr).Named("OnchainKeyring"), keys, donID, } } @@ -165,69 +162,12 @@ func (okr *onchainKeyring) Verify(key types.OnchainPublicKey, digest types.Confi // signature always covers exactly the leaves it was made over. The family is // the bundle's, and must match the report format the keyring dispatched on. func (okr *onchainKeyring) merkleSigningMessage(digest types.ConfigDigest, seqNr uint64, r ocr3types.ReportWithInfo[llotypes.ReportInfo]) (protocol.MerkleHash, error) { - root, err := okr.merkleRoots.root(r.Report) + bundle, err := protocol.LoadMerkleBundle(r.Report) if err != nil { return protocol.MerkleHash{}, err } - if root.family != r.Info.ReportFormat { - return protocol.MerkleHash{}, fmt.Errorf("bundle family %s does not match report format %s", root.family, r.Info.ReportFormat) + if bundle.Family != r.Info.ReportFormat { + return protocol.MerkleHash{}, fmt.Errorf("bundle family %s does not match report format %s", bundle.Family, r.Info.ReportFormat) } - return protocol.MerkleSigningMessage(digest, seqNr, root.family, root.leafCount, root.root), nil -} - -// merkleRootCacheSize bounds the bundle roots the keyring remembers. libocr -// verifies every peer's signature over the same bundle, so a few recent -// rounds are enough to compute each root once. -const merkleRootCacheSize = 64 - -// merkleRootCache memoizes bundle roots by the hash of the bundle bytes. -type merkleRootCache struct { - mu sync.Mutex - size int - entries map[[32]byte]merkleRoot - order [][32]byte -} - -type merkleRoot struct { - family llotypes.ReportFormat - root protocol.MerkleHash - leafCount uint32 -} - -func newMerkleRootCache(size int) *merkleRootCache { - return &merkleRootCache{size: size, entries: make(map[[32]byte]merkleRoot, size)} -} - -// root decodes the bundle and returns its family, root and leaf count, from -// the cache when the same bytes were seen before. -func (c *merkleRootCache) root(bundle []byte) (merkleRoot, error) { - key := sha256.Sum256(bundle) - c.mu.Lock() - cached, ok := c.entries[key] - c.mu.Unlock() - if ok { - return cached, nil - } - - decoded, err := protocol.DecodeMerkleBundle(bundle) - if err != nil { - return merkleRoot{}, err - } - root, err := protocol.MerkleBundleRoot(decoded) - if err != nil { - return merkleRoot{}, err - } - entry := merkleRoot{family: llotypes.ReportFormat(decoded.Family), root: root, leafCount: uint32(len(decoded.Leaves))} //nolint:gosec // bounded by protocol.MaxMerkleBundleLeaves on decode - - c.mu.Lock() - defer c.mu.Unlock() - if _, ok := c.entries[key]; !ok { - if len(c.order) == c.size { - delete(c.entries, c.order[0]) - c.order = c.order[1:] - } - c.entries[key] = entry - c.order = append(c.order, key) - } - return entry, nil + return protocol.MerkleSigningMessage(digest, seqNr, bundle.Family, bundle.LeafCount, bundle.Root), nil } diff --git a/llo/keyring/keyring_test.go b/llo/keyring/keyring_test.go index 5b969cb..339e7e1 100644 --- a/llo/keyring/keyring_test.go +++ b/llo/keyring/keyring_test.go @@ -2,7 +2,6 @@ package keyring import ( crand "crypto/rand" - "crypto/sha256" "fmt" "math" "math/rand/v2" @@ -246,22 +245,3 @@ func Test_Keyring_EVMMerkle(t *testing.T) { require.EqualError(t, err, "bundle family evm_merkle does not match report format evm_streamlined") }) } - -func Test_merkleRootCache_Evicts(t *testing.T) { - t.Parallel() - c := newMerkleRootCache(2) - bundles := make([][]byte, 3) - for i := range bundles { - b, err := protocol.EncodeMerkleBundle(&protocol.LLOMerkleBundleProto{ - Family: uint32(llotypes.ReportFormatEVMMerkle), - Leaves: []*protocol.LLOMerkleLeafProto{{ChannelID: uint32(i + 1), ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined)}}, //nolint:gosec // test - }) - require.NoError(t, err) - bundles[i] = b - _, err = c.root(b) - require.NoError(t, err) - } - assert.Len(t, c.entries, 2) - assert.Len(t, c.order, 2) - assert.NotContains(t, c.entries, sha256.Sum256(bundles[0])) -} diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go index 98a4a48..050c970 100644 --- a/llo/protocol/merkle.go +++ b/llo/protocol/merkle.go @@ -264,6 +264,10 @@ func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleDeliveryProto if err != nil { return nil, err } + return expandMerkleBundle(bundle, tree), nil +} + +func expandMerkleBundle(bundle *LLOMerkleBundleProto, tree merkleTree) []*LLOMerkleDeliveryProto { leafCount := uint32(len(bundle.Leaves)) //nolint:gosec // bounded by MaxMerkleBundleLeaves on decode deliveries := make([]*LLOMerkleDeliveryProto, len(bundle.Leaves)) for i, leaf := range bundle.Leaves { @@ -275,7 +279,7 @@ func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleDeliveryProto Proof: tree.proof(i), } } - return deliveries, nil + return deliveries } // EncodeMerkleDelivery encodes a delivery deterministically. diff --git a/llo/protocol/merkle_cache.go b/llo/protocol/merkle_cache.go new file mode 100644 index 0000000..da94c54 --- /dev/null +++ b/llo/protocol/merkle_cache.go @@ -0,0 +1,98 @@ +package protocol + +import ( + "crypto/sha256" + "errors" + "sync" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" +) + +// merkleBundleCacheSize bounds the bundles remembered. libocr verifies every +// peer's signature over the same bundle and the transmitter expands it after +// attestation, so a few recent rounds are enough to build each tree once. +const merkleBundleCacheSize = 32 + +// MerkleBundle is the tree built over the leaves of a bundle. It does not keep +// the leaves, which are as large as the encoded bundle. +type MerkleBundle struct { + Family llotypes.ReportFormat + LeafCount uint32 + Root MerkleHash + + tree merkleTree +} + +// Expand returns one delivery per leaf of encoded, in leaf order, each with its +// proof to the bundle root. It decodes encoded again and reuses the tree, so +// encoded must be the bytes this MerkleBundle was loaded from. +func (m *MerkleBundle) Expand(encoded []byte) ([]*LLOMerkleDeliveryProto, error) { + bundle, err := DecodeMerkleBundle(encoded) + if err != nil { + return nil, err + } + if llotypes.ReportFormat(bundle.Family) != m.Family || len(bundle.Leaves) != int(m.LeafCount) { + return nil, errors.New("bundle does not match the loaded merkle tree") + } + return expandMerkleBundle(bundle, m.tree), nil +} + +type merkleBundleCache struct { + mu sync.Mutex + size int + entries map[[32]byte]*MerkleBundle + order [][32]byte +} + +func newMerkleBundleCache(size int) *merkleBundleCache { + return &merkleBundleCache{size: size, entries: make(map[[32]byte]*MerkleBundle, size)} +} + +// load decodes the bundle and builds its tree, or returns the cached result +// when the same bytes were seen before. +func (c *merkleBundleCache) load(b []byte) (*MerkleBundle, error) { + key := sha256.Sum256(b) + c.mu.Lock() + cached, ok := c.entries[key] + c.mu.Unlock() + if ok { + return cached, nil + } + + bundle, err := DecodeMerkleBundle(b) + if err != nil { + return nil, err + } + tree, err := bundleTree(bundle) + if err != nil { + return nil, err + } + entry := &MerkleBundle{ + Family: llotypes.ReportFormat(bundle.Family), + LeafCount: uint32(len(bundle.Leaves)), //nolint:gosec // bounded by MaxMerkleBundleLeaves on decode + Root: tree.root(), + tree: tree, + } + + c.mu.Lock() + defer c.mu.Unlock() + if existing, ok := c.entries[key]; ok { + return existing, nil + } + if len(c.order) == c.size { + delete(c.entries, c.order[0]) + c.order = c.order[1:] + } + c.entries[key] = entry + c.order = append(c.order, key) + return entry, nil +} + +var sharedMerkleBundles = newMerkleBundleCache(merkleBundleCacheSize) + +// LoadMerkleBundle decodes a bundle and builds its tree. The tree is shared by +// the keyring, which signs the root, and the transmitter, which expands the +// attested bundle, so it is built once per bundle. +func LoadMerkleBundle(b []byte) (*MerkleBundle, error) { + return sharedMerkleBundles.load(b) +} diff --git a/llo/protocol/merkle_cache_test.go b/llo/protocol/merkle_cache_test.go new file mode 100644 index 0000000..ed3b1f4 --- /dev/null +++ b/llo/protocol/merkle_cache_test.go @@ -0,0 +1,75 @@ +package protocol + +import ( + "crypto/sha256" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" +) + +func Test_merkleBundleCache(t *testing.T) { + t.Parallel() + c := newMerkleBundleCache(2) + bundles := make([][]byte, 3) + for i := range bundles { + b, err := EncodeMerkleBundle(&LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*LLOMerkleLeafProto{{ChannelID: uint32(i + 1), ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined)}}, //nolint:gosec // test + }) + require.NoError(t, err) + bundles[i] = b + } + + t.Run("returns the same tree for the same bytes", func(t *testing.T) { + first, err := c.load(bundles[0]) + require.NoError(t, err) + second, err := c.load(bundles[0]) + require.NoError(t, err) + assert.Same(t, first, second) + }) + + t.Run("evicts the oldest entry", func(t *testing.T) { + for _, b := range bundles[1:] { + _, err := c.load(b) + require.NoError(t, err) + } + assert.Len(t, c.entries, 2) + assert.Len(t, c.order, 2) + assert.NotContains(t, c.entries, sha256.Sum256(bundles[0])) + }) + + t.Run("expands to the same deliveries as the uncached path", func(t *testing.T) { + loaded, err := c.load(bundles[2]) + require.NoError(t, err) + deliveries, err := loaded.Expand(bundles[2]) + require.NoError(t, err) + decoded, err := DecodeMerkleBundle(bundles[2]) + require.NoError(t, err) + root, err := MerkleBundleRoot(decoded) + require.NoError(t, err) + expanded, err := ExpandMerkleBundle(decoded) + require.NoError(t, err) + assert.Equal(t, root, loaded.Root) + assert.True(t, proto.Equal(expanded[0], deliveries[0])) + assert.Len(t, deliveries, len(expanded)) + }) + + t.Run("rejects bytes of another bundle", func(t *testing.T) { + loaded, err := c.load(bundles[2]) + require.NoError(t, err) + other, err := EncodeMerkleBundle(&LLOMerkleBundleProto{ + Family: uint32(llotypes.ReportFormatEVMMerkle), + Leaves: []*LLOMerkleLeafProto{ + {ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined)}, + {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined)}, + }, + }) + require.NoError(t, err) + _, err = loaded.Expand(other) + require.EqualError(t, err, "bundle does not match the loaded merkle tree") + }) +} diff --git a/llo/transmitter/transmitter.go b/llo/transmitter/transmitter.go index 9bd3689..25c65a0 100644 --- a/llo/transmitter/transmitter.go +++ b/llo/transmitter/transmitter.go @@ -234,14 +234,14 @@ func (t *transmitter) transmitMerkleBundle(ctx context.Context, digest types.Con // sub transmitters persist and send it like any other report, under the // family's report format. func expandMerkleBundle(report ocr3types.ReportWithInfo[llotypes.ReportInfo]) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) { - bundle, err := protocol.DecodeMerkleBundle(report.Report) + bundle, err := protocol.LoadMerkleBundle(report.Report) if err != nil { return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) } - if llotypes.ReportFormat(bundle.Family) != report.Info.ReportFormat { - return nil, fmt.Errorf("failed to expand %s bundle: bundle is of family %s", report.Info.ReportFormat, llotypes.ReportFormat(bundle.Family)) + if bundle.Family != report.Info.ReportFormat { + return nil, fmt.Errorf("failed to expand %s bundle: bundle is of family %s", report.Info.ReportFormat, bundle.Family) } - deliveries, err := protocol.ExpandMerkleBundle(bundle) + deliveries, err := bundle.Expand(report.Report) if err != nil { return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) } From 1c7b3f5fcd92d687377a19fe1c795eba9de4b85a Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Mon, 9 Nov 2026 16:31:11 +0000 Subject: [PATCH 8/9] llo/dev/v31: decouple the Merkle bundle leaf cap from the channel cap --- llo/protocol/merkle.go | 15 ++++++++++++--- llo/protocol/merkle_test.go | 4 ++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go index 050c970..2cc1303 100644 --- a/llo/protocol/merkle.go +++ b/llo/protocol/merkle.go @@ -37,9 +37,18 @@ const ( // MerkleSigningDomain prefixes the message a bundle root is signed under. MerkleSigningDomain = "LLO_MERKLE_V1" - // MaxMerkleBundleLeaves bounds the leaves of one bundle. A bundle holds at - // most one report per channel definition. - MaxMerkleBundleLeaves = MaxOutcomeChannelDefinitionsLength + // MaxMerkleBundleLeaves bounds the leaves of one bundle. It is a safety + // bound on bundles decoded from bytes, independent of the channel cap: a + // bundle is one report, so the libocr report count does not force it. Tree + // build time and memory grow linearly with the leaves, about 1 microsecond + // and 64 bytes per leaf, so a full bundle builds in about 15 ms and caches + // in about 1 MB. + // + // SplitMerkleBundle starts a new bundle at the byte cap, which binds first + // for reports of a few hundred bytes. When raising the channel cap, prefer + // more leaves per bundle over more bundles, and review the limits derived + // from the channel cap first. + MaxMerkleBundleLeaves = 16384 ) // MerkleHash is a node of the tree. diff --git a/llo/protocol/merkle_test.go b/llo/protocol/merkle_test.go index 4648ca7..17d25b6 100644 --- a/llo/protocol/merkle_test.go +++ b/llo/protocol/merkle_test.go @@ -246,7 +246,7 @@ func Test_MerkleBundle_Codec(t *testing.T) { err string }{ {"unknown family", &LLOMerkleBundleProto{Family: uint32(llotypes.ReportFormatJSON), Leaves: testLeaves(1)}, "merkle bundle has unknown family json"}, - {"no leaves", &LLOMerkleBundleProto{Family: uint32(evmMerkle)}, "merkle bundle has 0 leaves, expected between 1 and 2000"}, + {"no leaves", &LLOMerkleBundleProto{Family: uint32(evmMerkle)}, fmt.Sprintf("merkle bundle has 0 leaves, expected between 1 and %d", MaxMerkleBundleLeaves)}, {"non member leaf", &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: []*LLOMerkleLeafProto{{ChannelID: 1, ReportFormat: uint32(llotypes.ReportFormatJSON)}}}, "merkle bundle leaf 0: report format json is not a member of family evm_merkle"}, } for _, c := range cases { @@ -258,7 +258,7 @@ func Test_MerkleBundle_Codec(t *testing.T) { t.Run("too many leaves", func(t *testing.T) { _, err := DecodeMerkleBundle(encode(&LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(MaxMerkleBundleLeaves + 1)})) - require.EqualError(t, err, "merkle bundle has 2001 leaves, expected between 1 and 2000") + require.EqualError(t, err, fmt.Sprintf("merkle bundle has %d leaves, expected between 1 and %d", MaxMerkleBundleLeaves+1, MaxMerkleBundleLeaves)) }) t.Run("garbage", func(t *testing.T) { From 8b0c5119fae917e8744691119b1c754807004f07 Mon Sep 17 00:00:00 2001 From: Bruno Moura Date: Tue, 10 Nov 2026 08:09:44 +0000 Subject: [PATCH 9/9] llo/dev/v31: rename the Merkle per channel delivery to report Rename LLOMerkleDeliveryProto to LLOMerkleReportProto and the encode and decode functions, tests, fuzz corpus, comments and error strings to match. The wire format is unchanged. --- llo/dev/v31/doc.go | 8 +-- llo/protocol/llo_merkle.pb.go | 40 +++++------ llo/protocol/llo_merkle.proto | 6 +- llo/protocol/merkle.go | 50 +++++++------- llo/protocol/merkle_cache.go | 4 +- llo/protocol/merkle_cache_test.go | 8 +-- llo/protocol/merkle_test.go | 68 +++++++++---------- .../74c4f1b1275a82f0 | 0 .../evm/report_codec_evm_merkle.go | 32 ++++----- .../evm/report_codec_evm_merkle_test.go | 16 ++--- .../evm/report_codec_evm_streamlined.go | 2 +- .../dataengine/server_merkle_test.go | 8 +-- llo/transmitter/dataengine/transmitter.go | 2 +- llo/transmitter/transmitter.go | 34 +++++----- llo/transmitter/transmitter_merkle_test.go | 14 ++-- 15 files changed, 146 insertions(+), 146 deletions(-) rename llo/protocol/testdata/fuzz/{FuzzMerkleDelivery => FuzzMerkleReport}/74c4f1b1275a82f0 (100%) diff --git a/llo/dev/v31/doc.go b/llo/dev/v31/doc.go index 2b097d8..4658d09 100644 --- a/llo/dev/v31/doc.go +++ b/llo/dev/v31/doc.go @@ -206,7 +206,7 @@ // family (merkle.go), after the per report channels and before the staging // marker, split by size to fit MaxReportBytes. The keyring signs the bundle's // Merkle root once, and the transmitter expands the attested bundle into one -// delivery per channel with its proof. See protocol/merkle.go for the tree and +// report per channel with its proof. See protocol/merkle.go for the tree and // the signed message. // // The EVM family, llotypes.ReportFormatEVMMerkle in ReportInfo, covers every @@ -214,10 +214,10 @@ // join. Backfill reports follow the scheme of their target channel. // // A family is not tied to a destination chain. It fixes one signing key, one -// hash and signature scheme, and one delivery packer. The root is signed once +// hash and signature scheme, and one report packer. The root is signed once // with keys[family], so every member format must accept that signer. The EVM // family hashes with keccak256, signs with SignBlob over secp256k1 for -// ecrecover, and packs deliveries with ReportCodecEVMMerkle. A format on +// ecrecover, and packs reports with ReportCodecEVMMerkle. A format on // another key type needs its own family, since one signature cannot cover two // keys. Adding a family is a family constant, a protocol.MerkleFamily mapping, // a keyring case and a packer. Leaves commit to their member format and the @@ -226,7 +226,7 @@ // // The family is a report format rather than a signing scheme field on // ReportInfo so that a bundle of mixed codecs has a single format to select its -// key, and so the transmit queue and TransmitRequest recognise deliveries by +// key, and so the transmit queue and TransmitRequest recognise reports by // report_format without a schema or wire change. // // There is no protocol version gate. A build that predates the field drops it diff --git a/llo/protocol/llo_merkle.pb.go b/llo/protocol/llo_merkle.pb.go index 9f1e41b..111f32a 100644 --- a/llo/protocol/llo_merkle.pb.go +++ b/llo/protocol/llo_merkle.pb.go @@ -141,11 +141,11 @@ func (x *LLOMerkleLeafProto) GetReport() []byte { return nil } -// LLOMerkleDeliveryProto is one leaf of an attested bundle together with the +// LLOMerkleReportProto is one leaf of an attested bundle together with the // proof from the leaf to the bundle root. The root is not stored: the // verifier recomputes it from the leaf and the proof, and checks the // signatures over it. -type LLOMerkleDeliveryProto struct { +type LLOMerkleReportProto struct { state protoimpl.MessageState `protogen:"open.v1"` Family uint32 `protobuf:"varint,1,opt,name=family,proto3" json:"family,omitempty"` LeafCount uint32 `protobuf:"varint,2,opt,name=leafCount,proto3" json:"leafCount,omitempty"` @@ -158,20 +158,20 @@ type LLOMerkleDeliveryProto struct { sizeCache protoimpl.SizeCache } -func (x *LLOMerkleDeliveryProto) Reset() { - *x = LLOMerkleDeliveryProto{} +func (x *LLOMerkleReportProto) Reset() { + *x = LLOMerkleReportProto{} mi := &file_llo_merkle_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *LLOMerkleDeliveryProto) String() string { +func (x *LLOMerkleReportProto) String() string { return protoimpl.X.MessageStringOf(x) } -func (*LLOMerkleDeliveryProto) ProtoMessage() {} +func (*LLOMerkleReportProto) ProtoMessage() {} -func (x *LLOMerkleDeliveryProto) ProtoReflect() protoreflect.Message { +func (x *LLOMerkleReportProto) ProtoReflect() protoreflect.Message { mi := &file_llo_merkle_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -183,40 +183,40 @@ func (x *LLOMerkleDeliveryProto) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use LLOMerkleDeliveryProto.ProtoReflect.Descriptor instead. -func (*LLOMerkleDeliveryProto) Descriptor() ([]byte, []int) { +// Deprecated: Use LLOMerkleReportProto.ProtoReflect.Descriptor instead. +func (*LLOMerkleReportProto) Descriptor() ([]byte, []int) { return file_llo_merkle_proto_rawDescGZIP(), []int{2} } -func (x *LLOMerkleDeliveryProto) GetFamily() uint32 { +func (x *LLOMerkleReportProto) GetFamily() uint32 { if x != nil { return x.Family } return 0 } -func (x *LLOMerkleDeliveryProto) GetLeafCount() uint32 { +func (x *LLOMerkleReportProto) GetLeafCount() uint32 { if x != nil { return x.LeafCount } return 0 } -func (x *LLOMerkleDeliveryProto) GetLeafIndex() uint32 { +func (x *LLOMerkleReportProto) GetLeafIndex() uint32 { if x != nil { return x.LeafIndex } return 0 } -func (x *LLOMerkleDeliveryProto) GetLeaf() *LLOMerkleLeafProto { +func (x *LLOMerkleReportProto) GetLeaf() *LLOMerkleLeafProto { if x != nil { return x.Leaf } return nil } -func (x *LLOMerkleDeliveryProto) GetProof() [][]byte { +func (x *LLOMerkleReportProto) GetProof() [][]byte { if x != nil { return x.Proof } @@ -234,8 +234,8 @@ const file_llo_merkle_proto_rawDesc = "" + "\x12LLOMerkleLeafProto\x12\x1c\n" + "\tchannelID\x18\x01 \x01(\rR\tchannelID\x12\"\n" + "\freportFormat\x18\x02 \x01(\rR\freportFormat\x12\x16\n" + - "\x06report\x18\x03 \x01(\fR\x06report\"\xae\x01\n" + - "\x16LLOMerkleDeliveryProto\x12\x16\n" + + "\x06report\x18\x03 \x01(\fR\x06report\"\xac\x01\n" + + "\x14LLOMerkleReportProto\x12\x16\n" + "\x06family\x18\x01 \x01(\rR\x06family\x12\x1c\n" + "\tleafCount\x18\x02 \x01(\rR\tleafCount\x12\x1c\n" + "\tleafIndex\x18\x03 \x01(\rR\tleafIndex\x12*\n" + @@ -257,13 +257,13 @@ func file_llo_merkle_proto_rawDescGZIP() []byte { var file_llo_merkle_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_llo_merkle_proto_goTypes = []any{ - (*LLOMerkleBundleProto)(nil), // 0: v1.LLOMerkleBundleProto - (*LLOMerkleLeafProto)(nil), // 1: v1.LLOMerkleLeafProto - (*LLOMerkleDeliveryProto)(nil), // 2: v1.LLOMerkleDeliveryProto + (*LLOMerkleBundleProto)(nil), // 0: v1.LLOMerkleBundleProto + (*LLOMerkleLeafProto)(nil), // 1: v1.LLOMerkleLeafProto + (*LLOMerkleReportProto)(nil), // 2: v1.LLOMerkleReportProto } var file_llo_merkle_proto_depIdxs = []int32{ 1, // 0: v1.LLOMerkleBundleProto.leaves:type_name -> v1.LLOMerkleLeafProto - 1, // 1: v1.LLOMerkleDeliveryProto.leaf:type_name -> v1.LLOMerkleLeafProto + 1, // 1: v1.LLOMerkleReportProto.leaf:type_name -> v1.LLOMerkleLeafProto 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name diff --git a/llo/protocol/llo_merkle.proto b/llo/protocol/llo_merkle.proto index 5abb917..2fe05e2 100644 --- a/llo/protocol/llo_merkle.proto +++ b/llo/protocol/llo_merkle.proto @@ -6,7 +6,7 @@ option go_package = ".;protocol"; // WARNING // Use extreme caution making changes in this file // All changes MUST be backwards compatible -// Every oracle must build byte identical bundles, and deliveries are persisted +// Every oracle must build byte identical bundles, and reports are persisted // and verified by the Data Streams server and onchain. // LLOMerkleBundleProto is the report a signing family signs once per round. @@ -28,11 +28,11 @@ message LLOMerkleLeafProto { bytes report = 3; } -// LLOMerkleDeliveryProto is one leaf of an attested bundle together with the +// LLOMerkleReportProto is one leaf of an attested bundle together with the // proof from the leaf to the bundle root. The root is not stored: the // verifier recomputes it from the leaf and the proof, and checks the // signatures over it. -message LLOMerkleDeliveryProto { +message LLOMerkleReportProto { uint32 family = 1; uint32 leafCount = 2; uint32 leafIndex = 3; diff --git a/llo/protocol/merkle.go b/llo/protocol/merkle.go index 2cc1303..16bbbac 100644 --- a/llo/protocol/merkle.go +++ b/llo/protocol/merkle.go @@ -18,8 +18,8 @@ import ( // Channels with SigningSchemeMerkle are not signed one report at a time. // Reports groups them by signing family into bundle reports, the keyring signs // the Merkle root of each bundle once, and the transmitter expands an attested -// bundle into one delivery per leaf, carrying the proof from the leaf to the -// root. The verifier recomputes the root from the delivery and checks the +// bundle into one report per leaf, carrying the proof from the leaf to the +// root. The verifier recomputes the root from the report and checks the // signatures over it. // // The tree is domain separated as in RFC 6962. A leaf hashes as @@ -266,9 +266,9 @@ func MerkleBundleRoot(bundle *LLOMerkleBundleProto) (MerkleHash, error) { return tree.root(), nil } -// ExpandMerkleBundle returns one delivery per leaf of a decoded bundle, in +// ExpandMerkleBundle returns one report per leaf of a decoded bundle, in // leaf order, each with its proof to the bundle root. -func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleDeliveryProto, error) { +func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleReportProto, error) { tree, err := bundleTree(bundle) if err != nil { return nil, err @@ -276,11 +276,11 @@ func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleDeliveryProto return expandMerkleBundle(bundle, tree), nil } -func expandMerkleBundle(bundle *LLOMerkleBundleProto, tree merkleTree) []*LLOMerkleDeliveryProto { +func expandMerkleBundle(bundle *LLOMerkleBundleProto, tree merkleTree) []*LLOMerkleReportProto { leafCount := uint32(len(bundle.Leaves)) //nolint:gosec // bounded by MaxMerkleBundleLeaves on decode - deliveries := make([]*LLOMerkleDeliveryProto, len(bundle.Leaves)) + reports := make([]*LLOMerkleReportProto, len(bundle.Leaves)) for i, leaf := range bundle.Leaves { - deliveries[i] = &LLOMerkleDeliveryProto{ + reports[i] = &LLOMerkleReportProto{ Family: bundle.Family, LeafCount: leafCount, LeafIndex: uint32(i), //nolint:gosec // below leafCount @@ -288,37 +288,37 @@ func expandMerkleBundle(bundle *LLOMerkleBundleProto, tree merkleTree) []*LLOMer Proof: tree.proof(i), } } - return deliveries + return reports } -// EncodeMerkleDelivery encodes a delivery deterministically. -func EncodeMerkleDelivery(delivery *LLOMerkleDeliveryProto) ([]byte, error) { - return deterministicMarshal.Marshal(delivery) +// EncodeMerkleReport encodes a report deterministically. +func EncodeMerkleReport(report *LLOMerkleReportProto) ([]byte, error) { + return deterministicMarshal.Marshal(report) } -// DecodeMerkleDelivery decodes a delivery and returns the root its leaf and +// DecodeMerkleReport decodes a report and returns the root its leaf and // proof hash up to. The caller checks the signatures over // MerkleSigningMessage with that root. -func DecodeMerkleDelivery(b []byte) (*LLOMerkleDeliveryProto, MerkleHash, error) { - delivery := new(LLOMerkleDeliveryProto) - if err := proto.Unmarshal(b, delivery); err != nil { - return nil, MerkleHash{}, fmt.Errorf("failed to decode merkle delivery: %w", err) +func DecodeMerkleReport(b []byte) (*LLOMerkleReportProto, MerkleHash, error) { + report := new(LLOMerkleReportProto) + if err := proto.Unmarshal(b, report); err != nil { + return nil, MerkleHash{}, fmt.Errorf("failed to decode merkle report: %w", err) } - family := llotypes.ReportFormat(delivery.Family) + family := llotypes.ReportFormat(report.Family) if !IsMerkleFamily(family) { - return nil, MerkleHash{}, fmt.Errorf("merkle delivery has unknown family %s", family) + return nil, MerkleHash{}, fmt.Errorf("merkle report has unknown family %s", family) } - if delivery.LeafCount > MaxMerkleBundleLeaves { - return nil, MerkleHash{}, fmt.Errorf("merkle delivery has %d leaves, max %d", delivery.LeafCount, MaxMerkleBundleLeaves) + if report.LeafCount > MaxMerkleBundleLeaves { + return nil, MerkleHash{}, fmt.Errorf("merkle report has %d leaves, max %d", report.LeafCount, MaxMerkleBundleLeaves) } - if err := verifyMerkleLeaf(family, delivery.Leaf); err != nil { - return nil, MerkleHash{}, fmt.Errorf("merkle delivery: %w", err) + if err := verifyMerkleLeaf(family, report.Leaf); err != nil { + return nil, MerkleHash{}, fmt.Errorf("merkle report: %w", err) } - root, err := MerkleRootFromProof(MerkleLeafHash(family, delivery.Leaf), delivery.LeafIndex, delivery.LeafCount, delivery.Proof) + root, err := MerkleRootFromProof(MerkleLeafHash(family, report.Leaf), report.LeafIndex, report.LeafCount, report.Proof) if err != nil { - return nil, MerkleHash{}, fmt.Errorf("merkle delivery: %w", err) + return nil, MerkleHash{}, fmt.Errorf("merkle report: %w", err) } - return delivery, root, nil + return report, root, nil } // SplitMerkleBundle encodes leaves, in order, into as few consecutive bundles diff --git a/llo/protocol/merkle_cache.go b/llo/protocol/merkle_cache.go index da94c54..5e02481 100644 --- a/llo/protocol/merkle_cache.go +++ b/llo/protocol/merkle_cache.go @@ -23,10 +23,10 @@ type MerkleBundle struct { tree merkleTree } -// Expand returns one delivery per leaf of encoded, in leaf order, each with its +// Expand returns one report per leaf of encoded, in leaf order, each with its // proof to the bundle root. It decodes encoded again and reuses the tree, so // encoded must be the bytes this MerkleBundle was loaded from. -func (m *MerkleBundle) Expand(encoded []byte) ([]*LLOMerkleDeliveryProto, error) { +func (m *MerkleBundle) Expand(encoded []byte) ([]*LLOMerkleReportProto, error) { bundle, err := DecodeMerkleBundle(encoded) if err != nil { return nil, err diff --git a/llo/protocol/merkle_cache_test.go b/llo/protocol/merkle_cache_test.go index ed3b1f4..f614cb6 100644 --- a/llo/protocol/merkle_cache_test.go +++ b/llo/protocol/merkle_cache_test.go @@ -42,10 +42,10 @@ func Test_merkleBundleCache(t *testing.T) { assert.NotContains(t, c.entries, sha256.Sum256(bundles[0])) }) - t.Run("expands to the same deliveries as the uncached path", func(t *testing.T) { + t.Run("expands to the same reports as the uncached path", func(t *testing.T) { loaded, err := c.load(bundles[2]) require.NoError(t, err) - deliveries, err := loaded.Expand(bundles[2]) + reports, err := loaded.Expand(bundles[2]) require.NoError(t, err) decoded, err := DecodeMerkleBundle(bundles[2]) require.NoError(t, err) @@ -54,8 +54,8 @@ func Test_merkleBundleCache(t *testing.T) { expanded, err := ExpandMerkleBundle(decoded) require.NoError(t, err) assert.Equal(t, root, loaded.Root) - assert.True(t, proto.Equal(expanded[0], deliveries[0])) - assert.Len(t, deliveries, len(expanded)) + assert.True(t, proto.Equal(expanded[0], reports[0])) + assert.Len(t, reports, len(expanded)) }) t.Run("rejects bytes of another bundle", func(t *testing.T) { diff --git a/llo/protocol/merkle_test.go b/llo/protocol/merkle_test.go index 17d25b6..a96cb00 100644 --- a/llo/protocol/merkle_test.go +++ b/llo/protocol/merkle_test.go @@ -179,7 +179,7 @@ func Test_MerkleRootFromProof_Errors(t *testing.T) { } // The golden vectors are the shared reference for the verifier contract and -// the Data Streams server. Changing them breaks every delivery verifier. They +// the Data Streams server. Changing them breaks every verifier. They // were checked against an independent keccak256 implementation of the scheme // described in merkle.go. func Test_Merkle_GoldenVectors(t *testing.T) { @@ -206,10 +206,10 @@ func Test_Merkle_GoldenVectors(t *testing.T) { msg := MerkleSigningMessage(digest, seqNr, evmMerkle, uint32(len(bundle.Leaves)), root) assert.Equal(t, "82a749ca4b50caa0ea66a307bb3cffbc933bca6be71832179c775be8dee4ebac", hex.EncodeToString(msg[:])) - deliveries, err := ExpandMerkleBundle(bundle) + reports, err := ExpandMerkleBundle(bundle) require.NoError(t, err) - proofs := make([][]string, len(deliveries)) - for i, d := range deliveries { + proofs := make([][]string, len(reports)) + for i, d := range reports { for _, p := range d.Proof { proofs[i] = append(proofs[i], hex.EncodeToString(p)) } @@ -267,45 +267,45 @@ func Test_MerkleBundle_Codec(t *testing.T) { }) } -func Test_MerkleDelivery(t *testing.T) { +func Test_MerkleReport(t *testing.T) { bundle := &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(7)} root, err := MerkleBundleRoot(bundle) require.NoError(t, err) - deliveries, err := ExpandMerkleBundle(bundle) + reports, err := ExpandMerkleBundle(bundle) require.NoError(t, err) - require.Len(t, deliveries, 7) + require.Len(t, reports, 7) - for i, d := range deliveries { + for i, d := range reports { assert.Equal(t, uint32(i), d.LeafIndex) //nolint:gosec // test assert.Equal(t, uint32(7), d.LeafCount) assert.True(t, proto.Equal(bundle.Leaves[i], d.Leaf)) - b, err := EncodeMerkleDelivery(d) + b, err := EncodeMerkleReport(d) require.NoError(t, err) - decoded, got, err := DecodeMerkleDelivery(b) + decoded, got, err := DecodeMerkleReport(b) require.NoError(t, err) assert.Equal(t, root, got) assert.True(t, proto.Equal(d, decoded)) } - tamper := func(f func(d *LLOMerkleDeliveryProto)) (MerkleHash, error) { - d := proto.Clone(deliveries[3]).(*LLOMerkleDeliveryProto) + tamper := func(f func(d *LLOMerkleReportProto)) (MerkleHash, error) { + d := proto.Clone(reports[3]).(*LLOMerkleReportProto) f(d) - b, err := EncodeMerkleDelivery(d) + b, err := EncodeMerkleReport(d) require.NoError(t, err) - _, got, err := DecodeMerkleDelivery(b) + _, got, err := DecodeMerkleReport(b) return got, err } - for name, f := range map[string]func(d *LLOMerkleDeliveryProto){ - "report": func(d *LLOMerkleDeliveryProto) { d.Leaf.Report = append(d.Leaf.Report, 0) }, - "channel": func(d *LLOMerkleDeliveryProto) { d.Leaf.ChannelID++ }, - "format": func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMPremiumLegacy) }, - "index": func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 2 }, - "proof": func(d *LLOMerkleDeliveryProto) { d.Proof[0][0] ^= 1 }, + for name, f := range map[string]func(d *LLOMerkleReportProto){ + "report": func(d *LLOMerkleReportProto) { d.Leaf.Report = append(d.Leaf.Report, 0) }, + "channel": func(d *LLOMerkleReportProto) { d.Leaf.ChannelID++ }, + "format": func(d *LLOMerkleReportProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatEVMPremiumLegacy) }, + "index": func(d *LLOMerkleReportProto) { d.LeafIndex = 2 }, + "proof": func(d *LLOMerkleReportProto) { d.Proof[0][0] ^= 1 }, // A changed leaf count can still reach the root. The signed message // binds it, see Test_MerkleProof_EveryLeaf. - "leaf count": func(d *LLOMerkleDeliveryProto) { d.LeafCount = 9 }, + "leaf count": func(d *LLOMerkleReportProto) { d.LeafCount = 9 }, } { got, err := tamper(f) if err == nil { @@ -314,13 +314,13 @@ func Test_MerkleDelivery(t *testing.T) { } for name, c := range map[string]struct { - f func(d *LLOMerkleDeliveryProto) + f func(d *LLOMerkleReportProto) err string }{ - "family": {func(d *LLOMerkleDeliveryProto) { d.Family = uint32(llotypes.ReportFormatJSON) }, "merkle delivery has unknown family json"}, - "non member": {func(d *LLOMerkleDeliveryProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatJSON) }, "merkle delivery: report format json is not a member of family evm_merkle"}, - "no leaf": {func(d *LLOMerkleDeliveryProto) { d.Leaf = nil }, "merkle delivery: nil leaf"}, - "index range": {func(d *LLOMerkleDeliveryProto) { d.LeafIndex = 7 }, "merkle delivery: leaf index 7 out of range for 7 leaves"}, + "family": {func(d *LLOMerkleReportProto) { d.Family = uint32(llotypes.ReportFormatJSON) }, "merkle report has unknown family json"}, + "non member": {func(d *LLOMerkleReportProto) { d.Leaf.ReportFormat = uint32(llotypes.ReportFormatJSON) }, "merkle report: report format json is not a member of family evm_merkle"}, + "no leaf": {func(d *LLOMerkleReportProto) { d.Leaf = nil }, "merkle report: nil leaf"}, + "index range": {func(d *LLOMerkleReportProto) { d.LeafIndex = 7 }, "merkle report: leaf index 7 out of range for 7 leaves"}, } { _, err := tamper(c.f) require.EqualError(t, err, c.err, name) @@ -392,7 +392,7 @@ func mustEncodeBundle(t *testing.T, bundle *LLOMerkleBundleProto) []byte { return b } -func FuzzMerkleDelivery(f *testing.F) { +func FuzzMerkleReport(f *testing.F) { f.Add(uint16(1), uint16(0), []byte("a"), uint16(0)) f.Add(uint16(7), uint16(6), []byte("seven"), uint16(3)) f.Add(uint16(64), uint16(31), []byte{}, uint16(100)) @@ -405,23 +405,23 @@ func FuzzMerkleDelivery(f *testing.F) { root, err := MerkleBundleRoot(bundle) require.NoError(t, err) - deliveries, err := ExpandMerkleBundle(bundle) + reports, err := ExpandMerkleBundle(bundle) require.NoError(t, err) - b, err := EncodeMerkleDelivery(deliveries[i]) + b, err := EncodeMerkleReport(reports[i]) require.NoError(t, err) - _, got, err := DecodeMerkleDelivery(b) + _, got, err := DecodeMerkleReport(b) require.NoError(t, err) require.Equal(t, root, got) - // Flipping any bit of the delivery either fails to decode or no + // Flipping any bit of the report either fails to decode or no // longer reaches the root. The one exception is the leaf count, which // the root does not bind but the signed message does. bit := int(flip) % (len(b) * 8) tampered := append([]byte(nil), b...) tampered[bit/8] ^= 1 << (bit % 8) - d, got, err := DecodeMerkleDelivery(tampered) - if err == nil && got == root && d.LeafCount == deliveries[i].LeafCount { - require.True(t, proto.Equal(deliveries[i], d), "a changed delivery reached the root") + d, got, err := DecodeMerkleReport(tampered) + if err == nil && got == root && d.LeafCount == reports[i].LeafCount { + require.True(t, proto.Equal(reports[i], d), "a changed report reached the root") } }) } diff --git a/llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 b/llo/protocol/testdata/fuzz/FuzzMerkleReport/74c4f1b1275a82f0 similarity index 100% rename from llo/protocol/testdata/fuzz/FuzzMerkleDelivery/74c4f1b1275a82f0 rename to llo/protocol/testdata/fuzz/FuzzMerkleReport/74c4f1b1275a82f0 diff --git a/llo/reportcodec/evm/report_codec_evm_merkle.go b/llo/reportcodec/evm/report_codec_evm_merkle.go index 2191416..b4f9120 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle.go @@ -13,7 +13,7 @@ import ( protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" ) -// MerklePayloadTypes is the ABI of the payload an EVM Merkle delivery is +// MerklePayloadTypes is the ABI of the payload an EVM Merkle report is // verified with. It starts with the same five fields as PayloadTypes, so the // verifier proxy routes it by reportContext[0], the config digest, and the fee // manager reads the report from it unchanged. The Merkle fields follow. @@ -33,7 +33,7 @@ import ( // signers from such a payload and rejects it. var MerklePayloadTypes = getMerklePayloadTypes() -// MerkleReportContextTag marks reportContext[1] of a Merkle delivery payload. +// MerkleReportContextTag marks reportContext[1] of a Merkle report payload. const MerkleReportContextTag = protocol.MerkleSigningDomain func getMerklePayloadTypes() abi.Arguments { @@ -53,7 +53,7 @@ func getMerklePayloadTypes() abi.Arguments { })...) } -// MerkleReportContext returns the report context of a Merkle delivery payload. +// MerkleReportContext returns the report context of a Merkle report payload. func MerkleReportContext(digest ocr2types.ConfigDigest, seqNr uint64) (rc [3][32]byte) { rc[0] = [32]byte(digest) copy(rc[1][:], MerkleReportContextTag) @@ -61,23 +61,23 @@ func MerkleReportContext(digest ocr2types.ConfigDigest, seqNr uint64) (rc [3][32 return rc } -// ReportCodecEVMMerkle packs ReportFormatEVMMerkle deliveries for EVM +// ReportCodecEVMMerkle packs ReportFormatEVMMerkle reports for EVM // verifiers. It is a packer only: no channel uses the format, so there is // nothing to encode. type ReportCodecEVMMerkle struct{} -// Pack assembles a delivery, as expanded from an attested bundle, and the root +// Pack assembles a report, as expanded from an attested bundle, and the root // signatures into the payload for verifying on chain. -func (ReportCodecEVMMerkle) Pack(digest ocr2types.ConfigDigest, seqNr uint64, report ocr2types.Report, sigs []ocr2types.AttributedOnchainSignature) ([]byte, error) { - delivery, _, err := protocol.DecodeMerkleDelivery(report) +func (ReportCodecEVMMerkle) Pack(digest ocr2types.ConfigDigest, seqNr uint64, encoded ocr2types.Report, sigs []ocr2types.AttributedOnchainSignature) ([]byte, error) { + report, _, err := protocol.DecodeMerkleReport(encoded) if err != nil { return nil, err } - if family := llotypes.ReportFormat(delivery.Family); family != llotypes.ReportFormatEVMMerkle { - return nil, fmt.Errorf("expected a delivery of family %s, got %s", llotypes.ReportFormatEVMMerkle, family) + if family := llotypes.ReportFormat(report.Family); family != llotypes.ReportFormatEVMMerkle { + return nil, fmt.Errorf("expected a report of family %s, got %s", llotypes.ReportFormatEVMMerkle, family) } - proof := make([][32]byte, len(delivery.Proof)) - for i, p := range delivery.Proof { + proof := make([][32]byte, len(report.Proof)) + for i, p := range report.Proof { proof[i] = [32]byte(p) } rs, ss, vs, err := splitSignatures(sigs) @@ -86,14 +86,14 @@ func (ReportCodecEVMMerkle) Pack(digest ocr2types.ConfigDigest, seqNr uint64, re } payload, err := MerklePayloadTypes.Pack( MerkleReportContext(digest, seqNr), - delivery.Leaf.Report, + report.Leaf.Report, rs, ss, vs, - delivery.LeafCount, - delivery.LeafIndex, - delivery.Leaf.ChannelID, - delivery.Leaf.ReportFormat, + report.LeafCount, + report.LeafIndex, + report.Leaf.ChannelID, + report.Leaf.ReportFormat, proof, ) if err != nil { diff --git a/llo/reportcodec/evm/report_codec_evm_merkle_test.go b/llo/reportcodec/evm/report_codec_evm_merkle_test.go index e0d3453..b3c377d 100644 --- a/llo/reportcodec/evm/report_codec_evm_merkle_test.go +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -16,7 +16,7 @@ import ( protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" ) -// Test_ReportCodecEVMMerkle_Pack checks a packed delivery the way an onchain +// Test_ReportCodecEVMMerkle_Pack checks a packed report the way an onchain // verifier would: rebuild the leaf from the payload, hash it up to the root // with the proof, and recover the signers from the signed message. func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { @@ -46,10 +46,10 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { sigs[i].Signer = commontypes.OracleID(i) //nolint:gosec // test } - deliveries, err := protocol.ExpandMerkleBundle(bundle) + reports, err := protocol.ExpandMerkleBundle(bundle) require.NoError(t, err) - for i, d := range deliveries { - report, err := protocol.EncodeMerkleDelivery(d) + for i, d := range reports { + report, err := protocol.EncodeMerkleReport(d) require.NoError(t, err) payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) require.NoError(t, err) @@ -97,7 +97,7 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { // The fee manager and verifier proxy read a Merkle payload as a legacy // one, and a verifier without Merkle support rejects it. t.Run("decodes as a legacy payload and fails legacy verification", func(t *testing.T) { - report, err := protocol.EncodeMerkleDelivery(deliveries[1]) + report, err := protocol.EncodeMerkleReport(reports[1]) require.NoError(t, err) payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) require.NoError(t, err) @@ -124,8 +124,8 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { // The byte layout is the spec the onchain verifier is written against. t.Run("byte layout", func(t *testing.T) { - d := deliveries[1] - report, err := protocol.EncodeMerkleDelivery(d) + d := reports[1] + report, err := protocol.EncodeMerkleReport(d) require.NoError(t, err) payload, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, report, sigs) require.NoError(t, err) @@ -172,7 +172,7 @@ func Test_ReportCodecEVMMerkle_Pack(t *testing.T) { } }) - t.Run("rejects an invalid delivery", func(t *testing.T) { + t.Run("rejects an invalid report", func(t *testing.T) { _, err := ReportCodecEVMMerkle{}.Pack(digest, seqNr, []byte{0xff}, sigs) require.Error(t, err) }) diff --git a/llo/reportcodec/evm/report_codec_evm_streamlined.go b/llo/reportcodec/evm/report_codec_evm_streamlined.go index 639a670..392d435 100644 --- a/llo/reportcodec/evm/report_codec_evm_streamlined.go +++ b/llo/reportcodec/evm/report_codec_evm_streamlined.go @@ -105,7 +105,7 @@ func (rc ReportCodecEVMStreamlined) Verify(cd llotypes.ChannelDefinition) error // types the packed encoder cannot encode, and an ABI whose largest report // exceeds the uint16 length prefix Pack writes. Both fail every report of the // channel, the second only after it was signed. It also rejects -// SigningSchemeMerkle without a feed ID: a Merkle delivery goes through the +// SigningSchemeMerkle without a feed ID: a Merkle report goes through the // EVM verifier proxy, where the fee manager and the verifier read the feed ID // from the first 32 bytes of the report. // diff --git a/llo/transmitter/dataengine/server_merkle_test.go b/llo/transmitter/dataengine/server_merkle_test.go index c3ef2a6..d2b8352 100644 --- a/llo/transmitter/dataengine/server_merkle_test.go +++ b/llo/transmitter/dataengine/server_merkle_test.go @@ -35,16 +35,16 @@ func Test_server_transmit_EVMMerkle(t *testing.T) { {ChannelID: 2, ReportFormat: uint32(llotypes.ReportFormatEVMStreamlined), Report: []byte("two")}, }, } - deliveries, err := protocol.ExpandMerkleBundle(bundle) + reports, err := protocol.ExpandMerkleBundle(bundle) require.NoError(t, err) - delivery, err := protocol.EncodeMerkleDelivery(deliveries[1]) + report, err := protocol.EncodeMerkleReport(reports[1]) require.NoError(t, err) transmission := &Transmission{ ConfigDigest: types.ConfigDigest{1}, SeqNr: 7, Report: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ - Report: delivery, + Report: report, Info: llotypes.ReportInfo{LifeCycleStage: protocol.LifeCycleStageProduction, ReportFormat: llotypes.ReportFormatEVMMerkle}, }, Sigs: []types.AttributedOnchainSignature{{Signature: make([]byte, 65), Signer: 1}}, @@ -54,7 +54,7 @@ func Test_server_transmit_EVMMerkle(t *testing.T) { require.NotNil(t, got) assert.Equal(t, uint32(llotypes.ReportFormatEVMMerkle), got.ReportFormat) - want, err := evm.ReportCodecEVMMerkle{}.Pack(transmission.ConfigDigest, transmission.SeqNr, delivery, transmission.Sigs) + want, err := evm.ReportCodecEVMMerkle{}.Pack(transmission.ConfigDigest, transmission.SeqNr, report, transmission.Sigs) require.NoError(t, err) assert.Equal(t, want, got.Payload) } diff --git a/llo/transmitter/dataengine/transmitter.go b/llo/transmitter/dataengine/transmitter.go index c9b9ca1..e214522 100644 --- a/llo/transmitter/dataengine/transmitter.go +++ b/llo/transmitter/dataengine/transmitter.go @@ -259,7 +259,7 @@ func (mt *transmitter) Transmit( } // TransmitBatch enqueues reports that share a digest, seqNr and signatures, -// such as the deliveries of one Merkle bundle, for every server in one send +// such as the reports of one Merkle bundle, for every server in one send // to the commit loops. Like Transmit it returns once the batch is queued, so a // large batch costs one channel slot rather than one per report. func (mt *transmitter) TransmitBatch( diff --git a/llo/transmitter/transmitter.go b/llo/transmitter/transmitter.go index 25c65a0..110837c 100644 --- a/llo/transmitter/transmitter.go +++ b/llo/transmitter/transmitter.go @@ -43,7 +43,7 @@ type Transmitter interface { services.Service } -// batchTransmitter is a sub transmitter that can take the deliveries of one +// batchTransmitter is a sub transmitter that can take the reports of one // Merkle bundle at once, rather than one report per call. type batchTransmitter interface { TransmitBatch(ctx context.Context, digest types.ConfigDigest, seqNr uint64, reports []ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature) error @@ -202,10 +202,10 @@ func (t *transmitter) Transmit( return g.Wait() } -// transmitMerkleBundle hands every delivery of an attested bundle to each sub +// transmitMerkleBundle hands every report of an attested bundle to each sub // transmitter. libocr calls Transmit once for the whole bundle, under one // deadline, so a sub transmitter that takes a batch gets all of them in one -// call. One that does not gets them one at a time, and every delivery is +// call. One that does not gets them one at a time, and every report is // attempted even when an earlier one fails. func (t *transmitter) transmitMerkleBundle(ctx context.Context, digest types.ConfigDigest, seqNr uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature) error { reports, err := expandMerkleBundle(report) @@ -229,29 +229,29 @@ func (t *transmitter) transmitMerkleBundle(ctx context.Context, digest types.Con return g.Wait() } -// expandMerkleBundle turns an attested bundle into one delivery per leaf. Each -// delivery carries the leaf and its proof to the root the signatures cover, so +// expandMerkleBundle turns an attested bundle into one report per leaf. Each +// report carries the leaf and its proof to the root the signatures cover, so // sub transmitters persist and send it like any other report, under the // family's report format. -func expandMerkleBundle(report ocr3types.ReportWithInfo[llotypes.ReportInfo]) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) { - bundle, err := protocol.LoadMerkleBundle(report.Report) +func expandMerkleBundle(bundleReport ocr3types.ReportWithInfo[llotypes.ReportInfo]) ([]ocr3types.ReportWithInfo[llotypes.ReportInfo], error) { + bundle, err := protocol.LoadMerkleBundle(bundleReport.Report) if err != nil { - return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) + return nil, fmt.Errorf("failed to expand %s bundle: %w", bundleReport.Info.ReportFormat, err) } - if bundle.Family != report.Info.ReportFormat { - return nil, fmt.Errorf("failed to expand %s bundle: bundle is of family %s", report.Info.ReportFormat, bundle.Family) + if bundle.Family != bundleReport.Info.ReportFormat { + return nil, fmt.Errorf("failed to expand %s bundle: bundle is of family %s", bundleReport.Info.ReportFormat, bundle.Family) } - deliveries, err := bundle.Expand(report.Report) + merkleReports, err := bundle.Expand(bundleReport.Report) if err != nil { - return nil, fmt.Errorf("failed to expand %s bundle: %w", report.Info.ReportFormat, err) + return nil, fmt.Errorf("failed to expand %s bundle: %w", bundleReport.Info.ReportFormat, err) } - reports := make([]ocr3types.ReportWithInfo[llotypes.ReportInfo], len(deliveries)) - for i, delivery := range deliveries { - encoded, err := protocol.EncodeMerkleDelivery(delivery) + reports := make([]ocr3types.ReportWithInfo[llotypes.ReportInfo], len(merkleReports)) + for i, merkleReport := range merkleReports { + encoded, err := protocol.EncodeMerkleReport(merkleReport) if err != nil { - return nil, fmt.Errorf("failed to encode %s delivery: %w", report.Info.ReportFormat, err) + return nil, fmt.Errorf("failed to encode %s report: %w", bundleReport.Info.ReportFormat, err) } - reports[i] = ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: report.Info} + reports[i] = ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: bundleReport.Info} } return reports, nil } diff --git a/llo/transmitter/transmitter_merkle_test.go b/llo/transmitter/transmitter_merkle_test.go index b6ef448..92e987c 100644 --- a/llo/transmitter/transmitter_merkle_test.go +++ b/llo/transmitter/transmitter_merkle_test.go @@ -37,7 +37,7 @@ func (r *recordingSubTransmitter) FromAccount(context.Context) (types.Account, e return "", nil } -// batchingSubTransmitter takes a bundle's deliveries in one call. +// batchingSubTransmitter takes a bundle's reports in one call. type batchingSubTransmitter struct { recordingSubTransmitter batches [][]ocr3types.ReportWithInfo[llotypes.ReportInfo] @@ -96,15 +96,15 @@ func Test_transmitter_ExpandsMerkleBundle(t *testing.T) { for i, r := range sub.reports { assert.Equal(t, info, r.Info) assert.Equal(t, sigs, sub.sigs[i]) - delivery, got, err := protocol.DecodeMerkleDelivery(r.Report) + report, got, err := protocol.DecodeMerkleReport(r.Report) require.NoError(t, err) - assert.Equal(t, root, got, "delivery %d does not reach the signed root", i) - assert.Equal(t, uint32(i), delivery.LeafIndex) //nolint:gosec // test - assert.Equal(t, bundle.Leaves[i].ChannelID, delivery.Leaf.ChannelID) + assert.Equal(t, root, got, "report %d does not reach the signed root", i) + assert.Equal(t, uint32(i), report.LeafIndex) //nolint:gosec // test + assert.Equal(t, bundle.Leaves[i].ChannelID, report.Leaf.ChannelID) } } - t.Run("a batching sub transmitter gets every delivery in one call", func(t *testing.T) { + t.Run("a batching sub transmitter gets every report in one call", func(t *testing.T) { sub := &batchingSubTransmitter{} tr := &transmitter{lggr: logger.Test(t), subTransmitters: []Transmitter{sub}, onTransmit: &onTransmit{lggr: logger.Test(t)}} require.NoError(t, tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: info}, sigs)) @@ -113,7 +113,7 @@ func Test_transmitter_ExpandsMerkleBundle(t *testing.T) { assert.Empty(t, sub.reports) }) - t.Run("a failed delivery does not drop the rest", func(t *testing.T) { + t.Run("a failed report does not drop the rest", func(t *testing.T) { sub := &failingSubTransmitter{} tr := &transmitter{lggr: logger.Test(t), subTransmitters: []Transmitter{sub}, onTransmit: &onTransmit{lggr: logger.Test(t)}} err := tr.Transmit(ctx, types.ConfigDigest{1}, 9, ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: info}, sigs)