-
Notifications
You must be signed in to change notification settings - Fork 23
[CRE-4317] Implement EVM ocr3types.OnchainKeyring2 #469
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
pavel-raykov
wants to merge
8
commits into
develop
Choose a base branch
from
test-ocr3
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9ec3718
Minor.
pavel-raykov 082667f
Minor.
pavel-raykov 34b8f78
Minor.
pavel-raykov 4a4458d
Minor.
pavel-raykov b7488db
Minor.
pavel-raykov b4fde4f
Address comments.
pavel-raykov 7a7d341
Address comments.
pavel-raykov af63a12
Address comments.
pavel-raykov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| package keys | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/binary" | ||
| "fmt" | ||
| "math/big" | ||
| "strings" | ||
|
|
||
| "github.com/ethereum/go-ethereum/common" | ||
| "github.com/ethereum/go-ethereum/crypto" | ||
|
|
||
| "github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3types" | ||
| ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" | ||
|
|
||
| "github.com/smartcontractkit/chainlink-common/keystore" | ||
| ) | ||
|
|
||
| // CreateOCR3OnchainKeyring creates a new OCR3 onchain keyring. | ||
| // Note that key names are prefixed with PrefixEVM and PrefixOCR2Onchain (to preserve compatibility with OCR2) | ||
| // For example, a key named "test-key" will be stored at the path "evm/ocr2_onchain/test-key". | ||
| // The generic RI parameter is not used anywhere in the implementation. It acts as a defensive interface boundary to | ||
| // avoid signing a wrong type of reports. Note that it is not 100% bulletproof since one can also create a key with | ||
| // CreateOCR3OnchainKeyring[A] and then read it with ListOCR3OnchainKeyrings[B]. | ||
| func CreateOCR3OnchainKeyring[RI any](ctx context.Context, ks keystore.Keystore, keyringName string) (ocr3types.OnchainKeyring2[RI], error) { | ||
| onchainKeyPath := keystore.NewKeyPath(PrefixEVM, PrefixOCR2Onchain, keyringName) | ||
| createReq := keystore.CreateKeysRequest{ | ||
| Keys: []keystore.CreateKeyRequest{ | ||
| { | ||
| KeyName: onchainKeyPath.String(), | ||
| KeyType: keystore.ECDSA_S256, | ||
| }, | ||
| }, | ||
| } | ||
| resp, err := ks.CreateKeys(ctx, createReq) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if len(resp.Keys) != 1 { | ||
| return nil, fmt.Errorf("expected 1 key, got %d", len(resp.Keys)) | ||
| } | ||
| publicKey, err := crypto.UnmarshalPubkey(resp.Keys[0].KeyInfo.PublicKey) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| addr := crypto.PubkeyToAddress(*publicKey) | ||
| return &evmOnchainKeyring2[RI]{ks: ks, addr: addr, keyPath: onchainKeyPath}, nil | ||
| } | ||
|
|
||
| func ListOCR3OnchainKeyrings[RI any](ctx context.Context, ks keystore.Keystore, keyringNames ...string) ([]ocr3types.OnchainKeyring2[RI], error) { | ||
| var names []string | ||
| if len(keyringNames) > 0 { | ||
| for _, krn := range keyringNames { | ||
| names = append(names, keystore.NewKeyPath(PrefixEVM, PrefixOCR2Onchain, krn).String()) | ||
| } | ||
| } | ||
|
|
||
| getReq := keystore.GetKeysRequest{KeyNames: names} | ||
| resp, err := ks.GetKeys(ctx, getReq) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| keyrings := make([]ocr3types.OnchainKeyring2[RI], 0, len(resp.Keys)) | ||
| for _, key := range resp.Keys { | ||
| if !strings.HasPrefix(key.KeyInfo.Name, keystore.NewKeyPath(PrefixEVM, PrefixOCR2Onchain).String()) { | ||
| continue | ||
| } | ||
| keyPath := keystore.NewKeyPathFromString(key.KeyInfo.Name) | ||
| publicKey, err := crypto.UnmarshalPubkey(key.KeyInfo.PublicKey) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| addr := crypto.PubkeyToAddress(*publicKey) | ||
| keyrings = append(keyrings, &evmOnchainKeyring2[RI]{ks: ks, addr: addr, keyPath: keyPath}) | ||
| } | ||
| return keyrings, nil | ||
| } | ||
|
|
||
| var _ ocr3types.OnchainKeyring2[struct{}] = &evmOnchainKeyring2[struct{}]{} | ||
|
|
||
| type evmOnchainKeyring2[RI any] struct { | ||
| ks keystore.Keystore | ||
| addr common.Address | ||
| keyPath keystore.KeyPath | ||
| } | ||
|
|
||
| func (e *evmOnchainKeyring2[RI]) Sign(configDigest ocrtypes.ConfigDigest, seqNr uint64, report ocr3types.ReportWithInfo[RI]) (signature []byte, err error) { | ||
| hash := hashReport(configDigest, seqNr, report) | ||
| signResp, err := e.ks.Sign(context.Background(), keystore.SignRequest{ | ||
| KeyName: e.keyPath.String(), | ||
| Data: hash, | ||
| }) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return compressSignature(signResp.Signature), nil | ||
| } | ||
|
|
||
| func (e *evmOnchainKeyring2[RI]) Verify(publicKey ocrtypes.OnchainPublicKey, configDigest ocrtypes.ConfigDigest, seqNr uint64, report ocr3types.ReportWithInfo[RI], signature []byte) bool { | ||
| hash := hashReport(configDigest, seqNr, report) | ||
| recoveredPublicKey, err := crypto.SigToPub(hash, uncompressSignature(signature)) | ||
| if err != nil { | ||
| return false | ||
| } | ||
| signerAddress := crypto.PubkeyToAddress(*recoveredPublicKey) | ||
| return bytes.Equal(publicKey, signerAddress[:]) | ||
| } | ||
|
|
||
| func (e *evmOnchainKeyring2[RI]) Has(publicKey ocrtypes.OnchainPublicKey) bool { | ||
| return bytes.Equal(publicKey, e.addr.Bytes()) | ||
| } | ||
|
|
||
| func (e *evmOnchainKeyring2[RI]) MaxSignatureLength() int { | ||
| return 64 | ||
| } | ||
|
|
||
| func (e *evmOnchainKeyring2[RI]) DebugIdentifier() string { | ||
| return fmt.Sprintf("addr = %s, path = %s", e.addr.Hex(), e.keyPath.String()) | ||
| } | ||
|
|
||
| // Compresses the given ECDSA signature in its internal format (r, s, v) into the | ||
| // corresponding compressed format (r, s'), where s' in {s, n-s} depending on v. | ||
| func compressSignature(sig []byte) []byte { | ||
| // v is either 0 or 1; stores the recovery id of the underlying public key. | ||
| v := sig[64] | ||
| if v != 0 && v != 1 { | ||
| panic("v not in {0, 1}, cannot happen with cryptographic certainty") | ||
| } | ||
|
|
||
| result := make([]byte, 64) | ||
| copy(result, sig[:64]) | ||
|
|
||
| // In the smart contracts, a value of v=0 is assumed. (See https://github.com/smartcontractkit/offchain-reporting/blob/03dfcfe3e36f89a0d50678860b4b35ddf45a1c7e/contract3/src/OCR3ECDSAAttestationVerifierLib.sol#L62 .) | ||
| // So, if the recovery id is 1, s needs to flipped to "simulate" v=0. | ||
| if v == 1 { | ||
| // Extract the value of s from the signature bytes. | ||
| s := new(big.Int).SetBytes(result[32:64]) | ||
|
|
||
| // Get the order of the elliptic curve n, and compute s' = n - s. | ||
| N := crypto.S256().Params().N | ||
| s.Sub(N, s) | ||
|
|
||
| // Store s back into the result bytes. | ||
| s.FillBytes(result[32:64]) | ||
| } | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| // Uncompresses the given ECDSA signature in its external format (r, s') into the | ||
| // format expected internally (r, s', v=0). | ||
| // Note that uncompression does not guarantee that the resulting signature verifies | ||
| // using the "github.com/ethereum/go-ethereum/crypto".VerifySignature function. Instead, it guarantees that | ||
| // the correct public key is recovered using "github.com/ethereum/go-ethereum/crypto".SigToPub. | ||
| func uncompressSignature(sig []byte) []byte { | ||
| return append(sig, 0) | ||
| } | ||
|
|
||
| // hashReport computes an EVM-friendly cryptographic hash function over configDigest, seqNr, and reportWithInfo.Report. | ||
| // The main difference from OCR2 hashing (https://github.com/smartcontractkit/chainlink-evm/blob/b4068bf735e6e1af28602eece9e29a0bd31eed37/pkg/keys/v2/ocr2_onchain_keyring.go#L98) | ||
| // is that we hash the sequence number `seqNr` instead of `epoch||round||extraHash`. | ||
| // Domain separation is guaranteed because the result of this function is a Keccak hash computed over 96 bytes | ||
| // while the aforementioned OCR2 function is a Keccak hash computed over 128 bytes. | ||
| func hashReport[RI any](configDigest ocrtypes.ConfigDigest, seqNr uint64, report ocr3types.ReportWithInfo[RI]) []byte { | ||
|
pavel-raykov marked this conversation as resolved.
|
||
| data := make([]byte, 96) | ||
| copy(data, configDigest[:]) | ||
| binary.BigEndian.PutUint64(data[56:64], seqNr) | ||
| copy(data[64:96], crypto.Keccak256(report.Report)) | ||
| return crypto.Keccak256(data) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.