diff --git a/go.mod b/go.mod index 6478fa3..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 @@ -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,9 +145,10 @@ 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 + 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 @@ -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..4a76d13 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,19 +545,27 @@ 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= 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= @@ -575,6 +589,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 +634,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/dev/v31/doc.go b/llo/dev/v31/doc.go index 5e1f9eb..4658d09 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 +// 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 +// 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 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 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 +// 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 reports 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/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 new file mode 100644 index 0000000..bb5ff80 --- /dev/null +++ b/llo/dev/v31/merkle.go @@ -0,0 +1,92 @@ +package llo + +import ( + "slices" + + llotypes "github.com/smartcontractkit/chainlink-common/pkg/types/llo" + + protocol "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" + + "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" +) + +// merkleBundler collects the channel reports of a round that are signed as +// leaves, per signing family. +type merkleBundler struct { + 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, emitted func()) { + if b.leaves == nil { + b.leaves = map[llotypes.ReportFormat][]bundlerLeaf{} + } + b.leaves[family] = append(b.leaves[family], bundlerLeaf{ + leaf: &protocol.LLOMerkleLeafProto{ + ChannelID: channelID, + ReportFormat: uint32(format), + Report: report, + }, + source: source, + emitted: emitted, + }) +} + +// 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. 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) + } + slices.Sort(families) + + var rwis []ocr3types.ReportPlus[llotypes.ReportInfo] + for _, family := range families { + 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 { + 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 { + 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]{ + ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: bundle, + Info: llotypes.ReportInfo{ + LifeCycleStage: stage, + ReportFormat: family, + }, + }, + }) + } + } + return rwis +} diff --git a/llo/dev/v31/merkle_test.go b/llo/dev/v31/merkle_test.go new file mode 100644 index 0000000..e85f2ac --- /dev/null +++ b/llo/dev/v31/merkle_test.go @@ -0,0 +1,189 @@ +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: MaxReportBytes * 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), 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 95d3ad1..da75c04 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. @@ -109,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) @@ -120,6 +122,19 @@ 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 := 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, emitted) + continue + } + emitted() rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -153,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") @@ -165,6 +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 := 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, emitted) + continue + } + emitted() rwis = append(rwis, ocr3types.ReportPlus[llotypes.ReportInfo]{ ReportWithInfo: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ Report: encoded, @@ -176,6 +202,8 @@ func (p *Plugin) Reports(ctx context.Context, seqNr uint64, rawPrecursor ocr3_1t }) } + 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. if out.LifeCycleStage == protocol.LifeCycleStageStaging && len(rwis) < protocol.MaxReportCount { diff --git a/llo/keyring/keyring.go b/llo/keyring/keyring.go new file mode 100644 index 0000000..bd943f2 --- /dev/null +++ b/llo/keyring/keyring.go @@ -0,0 +1,173 @@ +// 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/protocol" + "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)) + } + 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) + } + } + 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) + } + 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) + } + } + + 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) { + bundle, err := protocol.LoadMerkleBundle(r.Report) + if err != nil { + return protocol.MerkleHash{}, err + } + 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, bundle.Family, bundle.LeafCount, bundle.Root), nil +} diff --git a/llo/keyring/keyring_test.go b/llo/keyring/keyring_test.go new file mode 100644 index 0000000..339e7e1 --- /dev/null +++ b/llo/keyring/keyring_test.go @@ -0,0 +1,247 @@ +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" + "google.golang.org/protobuf/proto" + + "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" + "github.com/smartcontractkit/chainlink-data-streams/llo/protocol" +) + +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 +} + +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") + }) +} 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..111f32a --- /dev/null +++ b/llo/protocol/llo_merkle.pb.go @@ -0,0 +1,296 @@ +// 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 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"` + 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 +} + +// 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 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"` + 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 *LLOMerkleReportProto) Reset() { + *x = LLOMerkleReportProto{} + mi := &file_llo_merkle_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LLOMerkleReportProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LLOMerkleReportProto) ProtoMessage() {} + +func (x *LLOMerkleReportProto) 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 LLOMerkleReportProto.ProtoReflect.Descriptor instead. +func (*LLOMerkleReportProto) Descriptor() ([]byte, []int) { + return file_llo_merkle_proto_rawDescGZIP(), []int{2} +} + +func (x *LLOMerkleReportProto) GetFamily() uint32 { + if x != nil { + return x.Family + } + return 0 +} + +func (x *LLOMerkleReportProto) GetLeafCount() uint32 { + if x != nil { + return x.LeafCount + } + return 0 +} + +func (x *LLOMerkleReportProto) GetLeafIndex() uint32 { + if x != nil { + return x.LeafIndex + } + return 0 +} + +func (x *LLOMerkleReportProto) GetLeaf() *LLOMerkleLeafProto { + if x != nil { + return x.Leaf + } + return nil +} + +func (x *LLOMerkleReportProto) 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\"\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" + + "\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 + (*LLOMerkleReportProto)(nil), // 2: v1.LLOMerkleReportProto +} +var file_llo_merkle_proto_depIdxs = []int32{ + 1, // 0: v1.LLOMerkleBundleProto.leaves: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 + 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..2fe05e2 --- /dev/null +++ b/llo/protocol/llo_merkle.proto @@ -0,0 +1,43 @@ +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 reports 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 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; +} + +// 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; +} + +// 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 LLOMerkleReportProto { + 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..16bbbac --- /dev/null +++ b/llo/protocol/merkle.go @@ -0,0 +1,365 @@ +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 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 +// 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. 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. +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. 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.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 +} + +// 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 0, false, nil + case llotypes.SigningSchemeMerkle: + 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 family, true, nil + default: + 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) { + 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 report per leaf of a decoded bundle, in +// leaf order, each with its proof to the bundle root. +func ExpandMerkleBundle(bundle *LLOMerkleBundleProto) ([]*LLOMerkleReportProto, error) { + tree, err := bundleTree(bundle) + if err != nil { + return nil, err + } + return expandMerkleBundle(bundle, tree), nil +} + +func expandMerkleBundle(bundle *LLOMerkleBundleProto, tree merkleTree) []*LLOMerkleReportProto { + leafCount := uint32(len(bundle.Leaves)) //nolint:gosec // bounded by MaxMerkleBundleLeaves on decode + reports := make([]*LLOMerkleReportProto, len(bundle.Leaves)) + for i, leaf := range bundle.Leaves { + reports[i] = &LLOMerkleReportProto{ + Family: bundle.Family, + LeafCount: leafCount, + LeafIndex: uint32(i), //nolint:gosec // below leafCount + Leaf: leaf, + Proof: tree.proof(i), + } + } + return reports +} + +// EncodeMerkleReport encodes a report deterministically. +func EncodeMerkleReport(report *LLOMerkleReportProto) ([]byte, error) { + return deterministicMarshal.Marshal(report) +} + +// 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 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(report.Family) + if !IsMerkleFamily(family) { + return nil, MerkleHash{}, fmt.Errorf("merkle report has unknown family %s", family) + } + if report.LeafCount > MaxMerkleBundleLeaves { + return nil, MerkleHash{}, fmt.Errorf("merkle report has %d leaves, max %d", report.LeafCount, MaxMerkleBundleLeaves) + } + if err := verifyMerkleLeaf(family, report.Leaf); err != nil { + return nil, MerkleHash{}, fmt.Errorf("merkle report: %w", err) + } + root, err := MerkleRootFromProof(MerkleLeafHash(family, report.Leaf), report.LeafIndex, report.LeafCount, report.Proof) + if err != nil { + return nil, MerkleHash{}, fmt.Errorf("merkle report: %w", err) + } + return report, 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_cache.go b/llo/protocol/merkle_cache.go new file mode 100644 index 0000000..5e02481 --- /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 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) ([]*LLOMerkleReportProto, 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..f614cb6 --- /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 reports as the uncached path", func(t *testing.T) { + loaded, err := c.load(bundles[2]) + require.NoError(t, err) + reports, 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], reports[0])) + assert.Len(t, reports, 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/protocol/merkle_test.go b/llo/protocol/merkle_test.go new file mode 100644 index 0000000..a96cb00 --- /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 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[:])) + + reports, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + proofs := make([][]string, len(reports)) + for i, d := range reports { + 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)}, 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 { + 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, fmt.Sprintf("merkle bundle has %d leaves, expected between 1 and %d", MaxMerkleBundleLeaves+1, MaxMerkleBundleLeaves)) + }) + + t.Run("garbage", func(t *testing.T) { + _, err := DecodeMerkleBundle([]byte{0xff, 0xff}) + require.Error(t, err) + }) +} + +func Test_MerkleReport(t *testing.T) { + bundle := &LLOMerkleBundleProto{Family: uint32(evmMerkle), Leaves: testLeaves(7)} + root, err := MerkleBundleRoot(bundle) + require.NoError(t, err) + + reports, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + require.Len(t, reports, 7) + + 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 := EncodeMerkleReport(d) + require.NoError(t, err) + 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 *LLOMerkleReportProto)) (MerkleHash, error) { + d := proto.Clone(reports[3]).(*LLOMerkleReportProto) + f(d) + b, err := EncodeMerkleReport(d) + require.NoError(t, err) + _, got, err := DecodeMerkleReport(b) + return got, err + } + 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 *LLOMerkleReportProto) { 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 *LLOMerkleReportProto) + err string + }{ + "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) + } +} + +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 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)) + 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) + reports, err := ExpandMerkleBundle(bundle) + require.NoError(t, err) + b, err := EncodeMerkleReport(reports[i]) + require.NoError(t, err) + _, got, err := DecodeMerkleReport(b) + require.NoError(t, err) + require.Equal(t, root, got) + + // 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 := 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/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/FuzzMerkleReport/74c4f1b1275a82f0 b/llo/protocol/testdata/fuzz/FuzzMerkleReport/74c4f1b1275a82f0 new file mode 100644 index 0000000..8e7150f --- /dev/null +++ b/llo/protocol/testdata/fuzz/FuzzMerkleReport/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/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 new file mode 100644 index 0000000..b4f9120 --- /dev/null +++ b/llo/reportcodec/evm/report_codec_evm_merkle.go @@ -0,0 +1,103 @@ +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 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. +// +// 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. +// +// 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 report 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 report 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 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 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, encoded ocr2types.Report, sigs []ocr2types.AttributedOnchainSignature) ([]byte, error) { + report, _, err := protocol.DecodeMerkleReport(encoded) + if err != nil { + return nil, err + } + 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(report.Proof)) + for i, p := range report.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), + report.Leaf.Report, + rs, + ss, + vs, + report.LeafCount, + report.LeafIndex, + report.Leaf.ChannelID, + report.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..b3c377d --- /dev/null +++ b/llo/reportcodec/evm/report_codec_evm_merkle_test.go @@ -0,0 +1,179 @@ +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 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) { + 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 + } + + reports, err := protocol.ExpandMerkleBundle(bundle) + require.NoError(t, err) + 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) + + 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.EncodeMerkleReport(reports[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)) + } + }) + + // The byte layout is the spec the onchain verifier is written against. + t.Run("byte layout", func(t *testing.T) { + d := reports[1] + report, err := protocol.EncodeMerkleReport(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 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 ca060b8..392d435 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 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. // // 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/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/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.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..d2b8352 --- /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")}, + }, + } + reports, err := protocol.ExpandMerkleBundle(bundle) + require.NoError(t, err) + report, err := protocol.EncodeMerkleReport(reports[1]) + require.NoError(t, err) + + transmission := &Transmission{ + ConfigDigest: types.ConfigDigest{1}, + SeqNr: 7, + Report: ocr3types.ReportWithInfo[llotypes.ReportInfo]{ + Report: report, + 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, report, 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..e214522 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 the transmissions of one Transmit or TransmitBatch + // call, for every server, per send. + 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)), } } @@ -252,22 +254,39 @@ func (mt *transmitter) Transmit( seqNr uint64, report ocr3types.ReportWithInfo[llotypes.ReportInfo], sigs []types.AttributedOnchainSignature, +) error { + return mt.TransmitBatch(ctx, digest, seqNr, []ocr3types.ReportWithInfo[llotypes.ReportInfo]{report}, sigs) +} + +// TransmitBatch enqueues reports that share a digest, seqNr and signatures, +// 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( + 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 { - t := &Transmission{ - ServerURL: serverURL, - ConfigDigest: digest, - SeqNr: seqNr, - Report: report, - Sigs: sigs, - } - select { - case mt.commitCh <- t: - case <-ctx.Done(): - err = fmt.Errorf("failed to add transmission to commit channel: %w", ctx.Err()) + 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 { @@ -376,8 +395,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..110837c 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 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 +} + 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 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 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) + 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 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(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", bundleReport.Info.ReportFormat, err) + } + 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) + } + merkleReports, err := bundle.Expand(bundleReport.Report) + if err != nil { + return nil, fmt.Errorf("failed to expand %s bundle: %w", bundleReport.Info.ReportFormat, err) + } + 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 report: %w", bundleReport.Info.ReportFormat, err) + } + reports[i] = ocr3types.ReportWithInfo[llotypes.ReportInfo]{Report: encoded, Info: bundleReport.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..92e987c --- /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 reports 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]) + report, got, err := protocol.DecodeMerkleReport(r.Report) + require.NoError(t, err) + 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 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)) + require.Len(t, sub.batches, 1) + assert.Len(t, sub.batches[0], len(bundle.Leaves)) + assert.Empty(t, sub.reports) + }) + + 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) + 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..d92b2d2 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, 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, // or a grandfathered channel would freeze channel voting entirely. @@ -217,3 +220,55 @@ 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. 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 + revert := func(channelID llotypes.ChannelID) { + 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) + } + 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 7306cca..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" @@ -155,3 +156,41 @@ 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") + + // 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) +}