Skip to content

Commit

Permalink
Rebase peppermint branch to v0.38.5 (#2)
Browse files Browse the repository at this point in the history
* Added votes to header + added secp256k1 + other changes

* updated import

* txHash fix+update canonical rep

* removed sig size

* docs: fix consensus spec formatting (cometbft#3804)

* abci/server: recover from app panics in socket server (cometbft#3809)

fixes cometbft#3800

* abci/client: fix DATA RACE in gRPC client (cometbft#3798)

* Remove go func {}()

closes cometbft#357

- Remove go func(){}() that caused race condiditon

- To reproduce
	- add -race in make file to `install_abci`
	- Remove `CGO_ENABLED=0` & add -race to `install`

Signed-off-by: Marko Baricevic <[email protected]>

* remove -race

* fix data race

also, reorder callbacks similarly to socket client

* docs: "Writing a built-in Tendermint Core application in Go" guide (cometbft#3608)

* docs: go built-in guide

* fix package imports, add badger db, simplify Query

* newTendermint function

* working example

* finish the first guide

* add one more note

* add the second Golang guide - external ABCI app

* fix typos

* libs: Remove db from tendermint in favor of tendermint/tm-cmn (cometbft#3811)

* Remove db from tendemrint in favor of tendermint/tm-cmn

- remove db from `libs`
- update dependancy, there have been no breaking changes in the updated deps
	- https://github.com/grpc/grpc-go/releases
	- https://github.com/golang/protobuf/releases

Signed-off-by: Marko Baricevic <[email protected]>

* changelog add

* gofmt

* more gofmt

* docs: add A TOC to the Readme.md of ADR Section (cometbft#3820)

* ADR TOC in readme.md

* Added A TOC to the Readme.md of ADR Section

- Added table of contents to the Readme of the architecture section.
	- Easier to traverse and when you know what is there.
	- If the Adr's become viewable online it would help guide the user

Signed-off-by: Marko Baricevic <[email protected]>

* add tm-cmn to subprojects

* normalize word

* rpc: make max_body_bytes and max_header_bytes configurable (cometbft#3818)

* rpc: make max_body_bytes and max_header_bytes configurable

* update changelog pending

* p2p/conn: Add Bufferpool (cometbft#3664)

* use byte buffer pool to decreass allocs

* wrap to put buffer in defer

* wapper defer

* add dependency

* remove Gopkg,*

* add change log

* rpc: /broadcast_evidence (cometbft#3481)

* implement broadcast_duplicate_vote endpoint

* fix test_cover

* address comments

* address comments

* Update abci/example/kvstore/persistent_kvstore.go

Co-Authored-By: mossid <[email protected]>

* Update rpc/client/main_test.go

Co-Authored-By: mossid <[email protected]>

* address comments in progress

* reformat the code

* make linter happy

* make tests pass

* replace BroadcastDuplicateVote with BroadcastEvidence

* fix test

* fix endpoint name

* improve doc

* fix TestBroadcastEvidenceDuplicateVote

* Update rpc/core/evidence.go

Co-Authored-By: Thane Thomson <[email protected]>

* add changelog entry

* fix TestBroadcastEvidenceDuplicateVote

* mempool: make max_msg_bytes configurable (cometbft#3826)

* mempool: make max_msg_bytes configurable

* apply suggestions from code review

* update changelog pending

* apply suggestions from code review again

* rpc: return err if page is incorrect (less than 0 or greater than tot… (cometbft#3825)

* rpc: return err if page is incorrect (less than 0 or greater than total pages)

Fixes cometbft#3813

* fix rpc_test

* blockchain: Reorg reactor (cometbft#3561)

* go routines in blockchain reactor

* Added reference to the go routine diagram

* Initial commit

* cleanup

* Undo testing_logger change, committed by mistake

* Fix the test loggers

* pulled some fsm code into pool.go

* added pool tests

* changes to the design

added block requests under peer

moved the request trigger in the reactor poolRoutine, triggered now by a ticker

in general moved everything required for making block requests smarter in the poolRoutine

added a simple map of heights to keep track of what will need to be requested next

added a few more tests

* send errors to FSM in a different channel than blocks

send errors (RemovePeer) from switch on a different channel than the
one receiving blocks
renamed channels
added more pool tests

* more pool tests

* lint errors

* more tests

* more tests

* switch fast sync to new implementation

* fixed data race in tests

* cleanup

* finished fsm tests

* address golangci comments :)

* address golangci comments :)

* Added timeout on next block needed to advance

* updating docs and cleanup

* fix issue in test from previous cleanup

* cleanup

* Added termination scenarios, tests and more cleanup

* small fixes to adr, comments and cleanup

* Fix bug in sendRequest()

If we tried to send a request to a peer not present in the switch, a
missing continue statement caused the request to be blackholed in a peer
that was removed and never retried.

While this bug was manifesting, the reactor kept asking for other
blocks that would be stored and never consumed. Added the number of
unconsumed blocks in the math for requesting blocks ahead of current
processing height so eventually there will be no more blocks requested
until the already received ones are consumed.

* remove bpPeer's didTimeout field

* Use distinct err codes for peer timeout and FSM timeouts

* Don't allow peers to update with lower height

* review comments from Ethan and Zarko

* some cleanup, renaming, comments

* Move block execution in separate goroutine

* Remove pool's numPending

* review comments

* fix lint, remove old blockchain reactor and duplicates in fsm tests

* small reorg around peer after review comments

* add the reactor spec

* verify block only once

* review comments

* change to int for max number of pending requests

* cleanup and godoc

* Add configuration flag fast sync version

* golangci fixes

* fix config template

* move both reactor versions under blockchain

* cleanup, golint, renaming stuff

* updated documentation, fixed more golint warnings

* integrate with behavior package

* sync with master

* gofmt

* add changelog_pending entry

* move to improvments

* suggestion to changelog entry

* Renamed wire.go to codec.go (cometbft#3827)

* Renamed wire.go to codec.go

- Wire was the previous name of amino
- Codec describes the file better than `wire` & `amino`

Signed-off-by: Marko Baricevic <[email protected]>

* ide error

* rename amino.go to codec.go

* docs: add guides to docs (cometbft#3830)

* add staticcheck linting (cometbft#3828)

cleanup to add linter

    grpc change:
        https://godoc.org/google.golang.org/grpc#WithContextDialer
        https://godoc.org/google.golang.org/grpc#WithDialer
        grpc/grpc-go#2627
    prometheous change:
        due to UninstrumentedHandler, being deprecated in the future
    empty branch = empty if or else statement
        didn't delete them entirely but commented
        couldn't find a reason to have them
    could not replicate the issue cometbft#3406
        but if want to keep it commented then we should comment out the if statement as well

* types: move MakeVote / MakeBlock functions (cometbft#3819)

to the types package

Paritally Fixes cometbft#3584

* p2p: Fix error logging for connection stop (cometbft#3824)

* p2p: fix false-positive error logging when stopping connections

This changeset fixes two types of false-positive errors occurring during
connection shutdown.

The first occurs when the process invokes FlushStop() or Stop() on a
connection. While the previous behavior did properly wait for the sendRoutine
to finish, it did not notify the recvRoutine that the connection was shutting
down. This would cause the recvRouting to receive and error when reading and
log this error. The changeset fixes this by notifying the recvRoutine that
the connection is shutting down.

The second occurs when the connection is terminated (gracefully) by the other side.
The recvRoutine would get an EOF error during the read, log it, and stop the connection
with an error. The changeset detects EOF and gracefully shuts down the connection.

* bring back the comment about flushing

* add changelog entry

* listen for quitRecvRoutine too

* we have to call stopForError

Otherwise peer won't be removed from the peer set and maybe readded
later.

* p2p: Do not write 'Couldn't connect to any seeds' if there are no seeds (cometbft#3834)

* Do not write 'Couldn't connect to any seeds' if there are no seeds

* changelog

* remove privValUpgrade

* Fix typo in changelog

* Update CHANGELOG_PENDING.md

Co-Authored-By: Marko <[email protected]>

I'm setting up all peers dynamically by calling dial_peers, so p2p.seeds in configs is empty, and I'm seeing error log a lot in logs.

* docs: add a footer to guides (cometbft#3835)

* docs: "Writing a Tendermint Core application in Kotlin (gRPC)" guide (cometbft#3838)

* add abci grpc kotlin guide

* Update docs/guides/kotlin.md

Co-Authored-By: Anton Kaliaev <[email protected]>

* Update docs/guides/kotlin.md

Co-Authored-By: Anton Kaliaev <[email protected]>

* Update docs/guides/kotlin.md

Co-Authored-By: Anton Kaliaev <[email protected]>

* Update kotlin.md

* node: allow replacing existing p2p.Reactor(s)  (cometbft#3846)

* node: allow replacing existing p2p.Reactor(s)

using [`CustomReactors`
option](https://godoc.org/github.com/tendermint/tendermint/node#CustomReactors).
Warning: beware of accidental name clashes. Here is the list of existing
reactors: MEMPOOL, BLOCKCHAIN, CONSENSUS, EVIDENCE, PEX.

* check the absence of "CUSTOM" prefix

* merge 2 tests

* add doc.go to node package

* gocritic (1/2) (cometbft#3836)

    Add gocritic as a linter

    The linting is not complete, but should i complete in this PR or in a following.

    23 files have been touched so it may be better to do in a following PR


Commits:

* Add gocritic to linting

- Added gocritic to linting

Signed-off-by: Marko Baricevic <[email protected]>

* gocritic

* pr comments

* remove switch in cmdBatch

* tm-cmn to tm-db (cometbft#3850)

* tm-cmn to tm-db

* go.mod changes

* go.mod changes

* more go.mod

* fix tm-db

* ci fix, pending change

* version tmdb (cometbft#3854)

* txindexer: Refactor Tx Search Aggregation (cometbft#3851)

- Replace the previous intersect call, which was called at each query condition, with a map intersection.
- Replace fmt.Sprintf with string()

closes: cometbft#3076

Benchmarks

```
Old
goos: darwin
goarch: amd64
pkg: github.com/tendermint/tendermint/state/txindex/kv
BenchmarkTxSearch-4   	     200	 103641206 ns/op	 7998416 B/op	   71171 allocs/op
PASS
ok  	github.com/tendermint/tendermint/state/txindex/kv	26.019s

New
goos: darwin
goarch: amd64
pkg: github.com/tendermint/tendermint/state/txindex/kv
BenchmarkTxSearch-4   	    1000	  38615024 ns/op	13515226 B/op	  166460 allocs/op
PASS
ok  	github.com/tendermint/tendermint/state/txindex/kv	53.618s
```

~62% performance improvement

Commits:

* Refactor tx search

* Add pending changelog entry

* Add tx search benchmarking

* remove intermediate hashes list

also reset timer in BenchmarkTxSearch
and fix other benchmark

* fix import

* Add test cases

* Fix searching

* Replace fmt.Sprintf with string

* Update state/txindex/kv/kv.go

Co-Authored-By: Anton Kaliaev <[email protected]>

* Rename params

* Cleanup

* Check error in benchmarks

* release for v0.32.2

* Merge PR cometbft#3860: Update log v0.32.2

* changelog updates

* pr comments

* Fix for panic in signature verification if a peer sends a nil public key.

* update version.go

* Changelog update

* Update CHANGELOG.md

Co-Authored-By: Anton Kaliaev <[email protected]>

* update changelog

* p2p: only allow ed25519 pubkeys when connecting

also, recover from any possible failures in acceptPeers

Refs cometbft#4030

* update changelog and bump version to v0.32.6

* set the date to today

* cs: panic only when WAL#WriteSync fails

- modify WAL#Write and WAL#WriteSync to return an error

* types: validate Part#Proof

add ValidateBasic to crypto/merkle/SimpleProof

* cs: limit max bit array size and block parts count

* cs: test new limits

* cs: only assert important stuff

* update changelog and bump version to 0.32.7

* fixes after Ethan's review

* align max wal msg and max consensus msg sizes

* fix tests

* fix test

* use bor

* add data in commit

* remove votes from header

* new: add proposal results in vote

* fix: go mod

* new: add sidechannel proto objects

* new: add begin side blocker and deliver side tx

* new: add side tx results in begin side block

* add: add side tx results into request begin side-block

* chg: add address in sig object

* chg: add events in side block

* chg: allow empty sig

* chg: add flag to execute side-tx while not syncing

* chg: remove data from vote

* fix: use last byte on bigendian bytes

* fix: call sidetx result for string method

* feat: add rollback feature

* Use bor version v0.2.16

* Change log level tag from a single character to a full word

This will change logging format from:

D[2016-05-02|11:06:44.322]

to:

DEBUG[2016-05-02|11:06:44.322]

The purpose is to unify the logging with bor.

* consensus,scripts,state,store,types: change PartSetHeader total to uint32

* libs/log: add warn log level (cometbft#27)

* libs/log: add warn log level

* mardizzone/POS-1609: dev: chg: bump btcd dep and solve related issues

* mardizzone/POS-1609: dev: chg: solve vulnerabilities associated with some packages

* mardizzone/POS-1609: dev: chg: update bor version and replace tm-db

* mardizzone/POS-1609: dev: chg: bump go version

* mardizzone/POS-1609: dev: chg: bump go version to latest patch

* Changed the value of default maxNumInboundPeers and maxNumOutboundPeers

* made Stopping peer for error log as debig (cometbft#30)

* made dialing failed log as debug (cometbft#31)

* Added log to print number of peers (cometbft#32)

* added log to print number of peers

* update

* peppermint: changes to crypto

* Modified NewFilePV to generate secp256k1

* (temporarily) allow both tendermint/P*KeySecp256k1 and comet/P*KeySecp256k1Uncompressed to ease migration

* Forward-port disabled `MaxSignatureSize` checks (+ new ones needed)

* cherry pick secp256k1 migration commits + go mod tidy

* blocksync,consensus,crypto,libs,types: fix tests and more conflicts

* consensus,libs,types: fix tests, vulns from govuln and some lint errors

* ci: bump go version to 1.21.4

* Fixed `TestPubKeySecp256k1Address`

* crypto: enforce curve group order checks in genPrivKey

* abci,crypto: fix conflicts and tests

* types: fix TestInvalidPrecommitExtensions

* fix lint

* Extend kvstore example add with with key types

* Fix `TestReactorValidatorSetChanges`

* Fix UTs in `execution_test.go`

* Fix `TestEvidencePoolBasic`

* Fix `TestVoteExtension`

* test/e2e: use go 1.21.4 in docker

* test/e2e: use secp256k1 as default key type in testnet setup

* p2p/conn: use secp256k1 for p2p authentication

* p2p/conn: allow both secp256k1 and ed25519 key types for authentication

* all: address PR comments

* types,blocksync: fix lint + tests + bump deps complained by govuln

* crypto,state,test: resolve conflicts from v0.38.5

* abci: resolve conflicts from v0.38.5

* resolve go mod deps

* Revert "Merge branch 'v0.38.5-upstream' into raneet10/peppermint-changes"

This reverts commit 2706fc9, reversing
changes made to e404e0f.

* Revert "Revert "Merge branch 'v0.38.5-upstream' into raneet10/peppermint-changes""

This reverts commit fc56973.

* all: fix issue from merge

* docs: remove Warn log definition from ADR

* state: remove outdated comments

* types: increase MaxSignatureSize to 65 and unskip related tests

* cmd: minor refactor

Co-authored-by: Sergio Mena <[email protected]>

* libs/protoio: minor refactor

Co-authored-by: Sergio Mena <[email protected]>

* libs/pubsub: minor refactor

Co-authored-by: Sergio Mena <[email protected]>

* state: minor refactor

Co-authored-by: Sergio Mena <[email protected]>

* state: minor restructure in test

Co-authored-by: Sergio Mena <[email protected]>

* types: fix TestMaxCommitBytes + lint

* state,types: fix TestTxFilter and TestBlockMaxDataBytes

* types: fix TestBlockMaxDataBytesNoEvidence

* types: fix TestInvalidPrecommitExtensions

* abci,types: address comments

* crypto,proto: add secp256k1_uncompressed oneof in PublicKey proto message type

* remove revive from .golangci.yml

* remove replace of go-ethereum dep with bor and go mod tidy

---------

Co-authored-by: vaibhavchellani <[email protected]>
Co-authored-by: Alex Dupre <[email protected]>
Co-authored-by: Roman Useinov <[email protected]>
Co-authored-by: Marko <[email protected]>
Co-authored-by: Anton Kaliaev <[email protected]>
Co-authored-by: Jun Kimura <[email protected]>
Co-authored-by: zjubfd <[email protected]>
Co-authored-by: Anca Zamfir <[email protected]>
Co-authored-by: folex <[email protected]>
Co-authored-by: Ivan Kushmantsev <[email protected]>
Co-authored-by: Alexander Bezobchuk <[email protected]>
Co-authored-by: Ethan Buchman <[email protected]>
Co-authored-by: Zaki Manian <[email protected]>
Co-authored-by: Zaki Manian <[email protected]>
Co-authored-by: Jaynti Kanani <[email protected]>
Co-authored-by: Sai Kumar <[email protected]>
Co-authored-by: Krishna Upadhyaya <[email protected]>
Co-authored-by: Jerry <[email protected]>
Co-authored-by: Anshal Shukla <[email protected]>
Co-authored-by: marcello33 <[email protected]>
Co-authored-by: Vaibhav Jindal <[email protected]>
Co-authored-by: VaibhavJindal <[email protected]>
Co-authored-by: Pratik Patil <[email protected]>
Co-authored-by: Sergio Mena <[email protected]>
  • Loading branch information
1 parent 2cd0d1a commit 62a78ac
Show file tree
Hide file tree
Showing 27 changed files with 344 additions and 128 deletions.
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ linters:
- goconst
- gofmt
- goimports
- revive
- gosec
- gosimple
- govet
Expand Down
19 changes: 13 additions & 6 deletions crypto/encoding/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func init() {
json.RegisterType((*pc.PublicKey)(nil), "tendermint.crypto.PublicKey")
json.RegisterType((*pc.PublicKey_Ed25519)(nil), "tendermint.crypto.PublicKey_Ed25519")
json.RegisterType((*pc.PublicKey_Secp256K1)(nil), "tendermint.crypto.PublicKey_Secp256K1")
json.RegisterType((*pc.PublicKey_Secp256K1Uncompressed)(nil), "tendermint.crypto.PublicKey_Secp256K1Uncompressed")
}

// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey
Expand All @@ -28,8 +29,14 @@ func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
}
case secp256k1.PubKey:
kp = pc.PublicKey{
Sum: &pc.PublicKey_Secp256K1{
Secp256K1: k,
Sum: &pc.PublicKey_Secp256K1Uncompressed{
Secp256K1Uncompressed: k,
},
}
case secp256k1.PubKeyOld:
kp = pc.PublicKey{
Sum: &pc.PublicKey_Secp256K1Uncompressed{
Secp256K1Uncompressed: k,
},
}
default:
Expand All @@ -49,13 +56,13 @@ func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) {
pk := make(ed25519.PubKey, ed25519.PubKeySize)
copy(pk, k.Ed25519)
return pk, nil
case *pc.PublicKey_Secp256K1:
if len(k.Secp256K1) != secp256k1.PubKeySize {
case *pc.PublicKey_Secp256K1Uncompressed:
if len(k.Secp256K1Uncompressed) != secp256k1.PubKeySize {
return nil, fmt.Errorf("invalid size for PubKeySecp256k1. Got %d, expected %d",
len(k.Secp256K1), secp256k1.PubKeySize)
len(k.Secp256K1Uncompressed), secp256k1.PubKeySize)
}
pk := make(secp256k1.PubKey, secp256k1.PubKeySize)
copy(pk, k.Secp256K1)
copy(pk, k.Secp256K1Uncompressed)
return pk, nil
default:
return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
Expand Down
143 changes: 79 additions & 64 deletions crypto/secp256k1/secp256k1.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@ import (
"math/big"

secp256k1 "github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format
ethCrypto "github.com/ethereum/go-ethereum/crypto" //nolint:depguard

"github.com/cometbft/cometbft/crypto"
cmtjson "github.com/cometbft/cometbft/libs/json"
)

// -------------------------------------
const (
PrivKeyName = "tendermint/PrivKeySecp256k1"
PubKeyName = "tendermint/PubKeySecp256k1"
PrivKeyNameOld = "tendermint/PrivKeySecp256k1"
PubKeyNameOld = "tendermint/PubKeySecp256k1"
PrivKeyName = "comet/PrivKeySecp256k1Uncompressed"
PubKeyName = "comet/PubKeySecp256k1Uncompressed"

KeyType = "secp256k1"
PrivKeySize = 32
Expand All @@ -28,13 +29,34 @@ const (
func init() {
cmtjson.RegisterType(PubKey{}, PubKeyName)
cmtjson.RegisterType(PrivKey{}, PrivKeyName)
cmtjson.RegisterType(PubKeyOld{}, PubKeyNameOld)
cmtjson.RegisterType(PrivKeyOld{}, PrivKeyNameOld)
}

var _ crypto.PrivKey = PrivKey{}
var _ crypto.PrivKey = PrivKeyOld{}

// PrivKey implements PrivKey.
type PrivKey []byte

type PrivKeyOld []byte

func (privKey PrivKeyOld) Bytes() []byte {
return PrivKey(privKey).Bytes()
}
func (privKey PrivKeyOld) PubKey() crypto.PubKey {
return PrivKey(privKey).PubKey()
}
func (privKey PrivKeyOld) Equals(other crypto.PrivKey) bool {
return PrivKey(privKey).Equals(other)
}
func (privKey PrivKeyOld) Type() string {
return PrivKey(privKey).Type()
}
func (privKey PrivKeyOld) Sign(msg []byte) ([]byte, error) {
return PrivKey(privKey).Sign(msg)
}

// Bytes marshalls the private key using amino encoding.
func (privKey PrivKey) Bytes() []byte {
return []byte(privKey)
Expand All @@ -43,11 +65,14 @@ func (privKey PrivKey) Bytes() []byte {
// PubKey performs the point-scalar multiplication from the privKey on the
// generator point to get the pubkey.
func (privKey PrivKey) PubKey() crypto.PubKey {
_, pubkeyObject := secp256k1.PrivKeyFromBytes(privKey)

pk := pubkeyObject.SerializeCompressed()
privateObject, err := ethCrypto.ToECDSA(privKey)
if err != nil {
panic(err)
}

pk := ethCrypto.FromECDSAPub(&privateObject.PublicKey)
return PubKey(pk)

}

// Equals - you probably don't need to use this.
Expand Down Expand Up @@ -75,20 +100,21 @@ func genPrivKey(rand io.Reader) PrivKey {
d := new(big.Int)

for {
privKeyBytes = [PrivKeySize]byte{}
_, err := io.ReadFull(rand, privKeyBytes[:])
if err != nil {
panic(err)
}

d.SetBytes(privKeyBytes[:])
// break if we found a valid point (i.e. > 0 and < N == curverOrder)
// break if we found a valid point (i.e. > 0 and < N == curveOrder)
isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
if isValidFieldElement {
break
}
}

// crypto.CRandBytes is guaranteed to be 32 bytes long, so it can be
// casted to PrivKey.
return PrivKey(privKeyBytes[:])
}

Expand Down Expand Up @@ -124,47 +150,64 @@ func GenPrivKeySecp256k1(secret []byte) PrivKey {
}

// Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg.
// The returned signature will be of the form R || S (in lower-S form).
// The returned signature will be of the form R || S || V (in lower-S form).
func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
priv, _ := secp256k1.PrivKeyFromBytes(privKey)

sig, err := ecdsa.SignCompact(priv, crypto.Sha256(msg), false)
privateObject, err := ethCrypto.ToECDSA(privKey)
if err != nil {
return nil, err
}

// remove the first byte which is compactSigRecoveryCode
return sig[1:], nil
return ethCrypto.Sign(ethCrypto.Keccak256(msg), privateObject)
}

//-------------------------------------

var _ crypto.PubKey = PubKey{}
var _ crypto.PubKey = PubKeyOld{}

// PubKeySize (uncompressed) is comprised of 65 bytes for two field elements (x and y)
// and a prefix byte (0x04) to indicate that it is uncompressed.
const PubKeySize = 65

// PubKeySize is comprised of 32 bytes for one field element
// (the x-coordinate), plus one byte for the parity of the y-coordinate.
const PubKeySize = 33
// SigSize is the size of the ECDSA signature.
const SigSize = 65

// PubKey implements crypto.PubKey.
// It is the compressed form of the pubkey. The first byte depends is a 0x02 byte
// if the y-coordinate is the lexicographically largest of the two associated with
// the x-coordinate. Otherwise the first byte is a 0x03.
// This prefix is followed with the x-coordinate.
// It is the uncompressed form of the pubkey. The first byte is prefixed with 0x04.
// This prefix is followed with the (x,y)-coordinates.
type PubKey []byte
type PubKeyOld []byte

func (pubKey PubKeyOld) Address() crypto.Address {
return PubKey(pubKey).Address()
}

func (pubKey PubKeyOld) Bytes() []byte {
return PubKey(pubKey).Bytes()
}

func (pubKey PubKeyOld) String() string {
return PubKey(pubKey).String()
}

// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
func (pubKey PubKeyOld) Equals(other crypto.PubKey) bool {
return PubKey(pubKey).Equals(other)
}

func (pubKey PubKeyOld) Type() string {
return PubKey(pubKey).Type()
}

func (pubKey PubKeyOld) VerifySignature(msg []byte, sigStr []byte) bool {
return PubKey(pubKey).VerifySignature(msg, sigStr)
}

// Address returns a Ethereym style addresses: Last_20_Bytes(KECCAK256(pubkey))
func (pubKey PubKey) Address() crypto.Address {
if len(pubKey) != PubKeySize {
panic("length of pubkey is incorrect")
panic(fmt.Sprintf("length of pubkey is incorrect %d != %d", len(pubKey), PubKeySize))
}
hasherSHA256 := sha256.New()
_, _ = hasherSHA256.Write(pubKey) // does not error
sha := hasherSHA256.Sum(nil)

hasherRIPEMD160 := ripemd160.New()
_, _ = hasherRIPEMD160.Write(sha) // does not error

return crypto.Address(hasherRIPEMD160.Sum(nil))
return crypto.Address(ethCrypto.Keccak256(pubKey[1:])[12:])
}

// Bytes returns the pubkey marshaled with amino encoding.
Expand All @@ -187,41 +230,13 @@ func (pubKey PubKey) Type() string {
return KeyType
}

// VerifySignature verifies a signature of the form R || S.
// VerifySignature verifies a signature of the form R || S || V.
// It rejects signatures which are not in lower-S form.
func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool {
if len(sigStr) != 64 {
if len(sigStr) != SigSize {
return false
}

pub, err := secp256k1.ParsePubKey(pubKey)
if err != nil {
return false
}

// parse the signature:
signature := signatureFromBytes(sigStr)
// Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
// see: https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
// Serialize() would negate S value if it is over half order.
// Hence, if the signature is different after Serialize() if should be rejected.
var modifiedSignature, parseErr = ecdsa.ParseDERSignature(signature.Serialize())
if parseErr != nil {
return false
}
if !signature.IsEqual(modifiedSignature) {
return false
}

return signature.Verify(crypto.Sha256(msg), pub)
}

// Read Signature struct from R || S. Caller needs to ensure
// that len(sigStr) == 64.
func signatureFromBytes(sigStr []byte) *ecdsa.Signature {
var r secp256k1.ModNScalar
r.SetByteSlice(sigStr[:32])
var s secp256k1.ModNScalar
s.SetByteSlice(sigStr[32:64])
return ecdsa.NewSignature(&r, &s)
hash := ethCrypto.Keccak256(msg)
return ethCrypto.VerifySignature(pubKey, hash, sigStr[:64])
}
17 changes: 14 additions & 3 deletions crypto/secp256k1/secp256k1_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import (
"math/big"
"testing"

"github.com/stretchr/testify/require"

secp256k1 "github.com/btcsuite/btcd/btcec/v2"
"github.com/stretchr/testify/require"
)

func Test_genPrivKey(t *testing.T) {

empty := make([]byte, 32)
oneB := big.NewInt(1).Bytes()
onePadded := make([]byte, 32)
Expand Down Expand Up @@ -82,3 +80,16 @@ func TestSignatureVerificationAndRejectUpperS(t *testing.T) {
)
}
}

func TestGenEthPrivKey(t *testing.T) {
msg := []byte("We have lingered long enough on the shores of the cosmic ocean.")
priv := GenPrivKey()
t.Log("privkey ", priv)
sigStr, err := priv.Sign(msg)
require.NoError(t, err)
pub := priv.PubKey()
addr := pub.Address()
t.Log("address ", addr)
t.Log("pub ", pub)
t.Log("SigStr ", sigStr)
}
4 changes: 2 additions & 2 deletions crypto/secp256k1/secp256k1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ type keyData struct {
var secpDataTable = []keyData{
{
priv: "a96e62ed3955e65be32703f12d87b6b5cf26039ecfa948dc5107a495418e5330",
pub: "02950e1cdfcb133d6024109fd489f734eeb4502418e538c28481f22bce276f248c",
addr: "1CKZ9Nx4zgds8tU7nJHotKSDr4a9bYJCa3",
pub: "04950e1cdfcb133d6024109fd489f734eeb4502418e538c28481f22bce276f248ca0ca66092c9fe8adfbb8424bd92f26e170234c42df756075278ead79a8f5c4ae",
addr: "1PrkgVnuHLGZu4EUQGmXkGVuhTfn7t8DJK",
},
}

Expand Down
2 changes: 1 addition & 1 deletion evidence/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func TestEvidencePoolBasic(t *testing.T) {
next := pool.EvidenceFront()
assert.Equal(t, ev, next.Value.(types.Evidence))

const evidenceBytes int64 = 372
const evidenceBytes int64 = 374
evs, size = pool.PendingEvidence(evidenceBytes)
assert.Equal(t, 1, len(evs))
assert.Equal(t, evidenceBytes, size) // check that the size of the single evidence in bytes is correct
Expand Down
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ require (
github.com/btcsuite/btcd/btcutil v1.1.3
github.com/cometbft/cometbft-db v0.7.0
github.com/cosmos/gogoproto v1.4.11
github.com/ethereum/go-ethereum v1.13.4
github.com/go-git/go-git/v5 v5.11.0
github.com/gofrs/uuid v4.4.0+incompatible
github.com/google/uuid v1.4.0
Expand Down Expand Up @@ -103,7 +104,7 @@ require (
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/docker/cli v23.0.1+incompatible // indirect
github.com/docker/distribution v2.8.1+incompatible // indirect
github.com/docker/docker v23.0.1+incompatible // indirect
github.com/docker/docker v24.0.5+incompatible // indirect
github.com/docker/docker-credential-helpers v0.7.0 // indirect
github.com/docker/go-connections v0.4.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
Expand Down Expand Up @@ -140,7 +141,7 @@ require (
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.1.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect
github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 // indirect
github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a // indirect
github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe // indirect
Expand All @@ -165,6 +166,7 @@ require (
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/holiman/uint256 v1.2.3 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
Expand Down Expand Up @@ -195,7 +197,7 @@ require (
github.com/matoous/godox v0.0.0-20230222163458-006bad1f9d26 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mbilski/exhaustivestruct v1.2.0 // indirect
github.com/mgechev/revive v1.3.1 // indirect
Expand Down Expand Up @@ -225,6 +227,7 @@ require (
github.com/quasilyte/gogrep v0.5.0 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rs/zerolog v1.29.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/ryancurrah/gomodguard v1.3.0 // indirect
Expand Down
Loading

0 comments on commit 62a78ac

Please sign in to comment.