├── docs └── papers │ ├── hashcash.pdf │ ├── Cuckoo Cycle.pdf │ ├── Grin Slides.pdf │ ├── mimblewimble.pdf │ ├── Cuckoo hashing.pdf │ ├── On Stake and Consensus.pdf │ ├── Dandelion: Redesigning the Bitcoin Network for anonym.pdf │ ├── Simple Schnorr Multi-Signatures with Applications to Bitcoin.pdf │ ├── links │ └── OriginalWhitePaper.txt ├── go.mod ├── chain ├── chain_test.go ├── storage.go └── chain.go ├── AUTHORS ├── cmd └── node │ └── main.go ├── secp256k1zkp ├── pedersen.go ├── schnorr_test.go ├── constants.go └── schnorr.go ├── README.md ├── p2p ├── server.go ├── message_test.go ├── protocol.go ├── helpers.go ├── sync.go ├── handshake.go ├── pool.go ├── messages.go └── peer.go ├── consensus ├── consensus_test.go ├── locator.go ├── id.go ├── network.go ├── difficulty.go ├── transaction_test.go ├── proof.go ├── transaction.go ├── consensus.go ├── block_test.go └── block.go ├── storage └── mysql.go ├── cuckoo ├── siphash24.go ├── cuckoo_test.go └── cuckoo.go ├── go.sum └── LICENSE /docs/papers/hashcash.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/hashcash.pdf -------------------------------------------------------------------------------- /docs/papers/Cuckoo Cycle.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/Cuckoo Cycle.pdf -------------------------------------------------------------------------------- /docs/papers/Grin Slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/Grin Slides.pdf -------------------------------------------------------------------------------- /docs/papers/mimblewimble.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/mimblewimble.pdf -------------------------------------------------------------------------------- /docs/papers/Cuckoo hashing.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/Cuckoo hashing.pdf -------------------------------------------------------------------------------- /docs/papers/On Stake and Consensus.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/On Stake and Consensus.pdf -------------------------------------------------------------------------------- /docs/papers/Dandelion: Redesigning the Bitcoin Network for anonym.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/Dandelion: Redesigning the Bitcoin Network for anonym.pdf -------------------------------------------------------------------------------- /docs/papers/Simple Schnorr Multi-Signatures with Applications to Bitcoin.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dblokhin/gringo/HEAD/docs/papers/Simple Schnorr Multi-Signatures with Applications to Bitcoin.pdf -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/dblokhin/gringo 2 | 3 | require ( 4 | github.com/btcsuite/btcd v0.0.0-20181130015935-7d2daa5bfef2 5 | github.com/dchest/siphash v1.2.1 6 | github.com/go-sql-driver/mysql v1.4.1 7 | github.com/sirupsen/logrus v1.2.0 8 | github.com/yoss22/bulletproofs v0.0.0-20181219041900-c29397110419 9 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 10 | ) 11 | -------------------------------------------------------------------------------- /docs/papers/links: -------------------------------------------------------------------------------- 1 | 2 | Make a transactions: 3 | https://lists.launchpad.net/mimblewimble/msg00091.html 4 | https://lists.launchpad.net/mimblewimble/msg00087.html 5 | 6 | reducing transaction kernels: 7 | https://pastebin.com/aCdznJW1 8 | 9 | insights on Cuckoo cycle mining algorithm: 10 | https://www.reddit.com/r/Aeternity/comments/6vsot4/towards_a_more_egalitarian_pow_using_cuckoo_cycle/ -------------------------------------------------------------------------------- /chain/chain_test.go: -------------------------------------------------------------------------------- 1 | package chain 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "testing" 7 | ) 8 | 9 | func TestGenesisHash(t *testing.T) { 10 | hash := Testnet4.Hash() 11 | expected, _ := hex.DecodeString("0644cedb1acfdde4ee9e135ae61de3cbeb301b5f27a40a2c366da8e724292f20") 12 | 13 | if bytes.Compare(hash, expected) != 0 { 14 | t.Errorf("Genesis hash was %v wanted %x. Content:\n%x\n", 15 | hash, expected, Testnet4.Bytes()) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of Gringo Developers for copyright purposes. 2 | 3 | # If you are submitting a patch, please add your name or the name of the 4 | # organization which holds the copyright to this list in alphabetical order. 5 | 6 | # Names should be added to this file as 7 | # Name 8 | # The email address is not required for organizations. 9 | # Please keep the list sorted. 10 | 11 | 12 | # Individual Persons 13 | Dmitriy Blokhin 14 | John Yossarian 15 | 16 | # Organizations 17 | 18 | -------------------------------------------------------------------------------- /cmd/node/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/dblokhin/gringo/p2p" 5 | "github.com/sirupsen/logrus" 6 | "github.com/dblokhin/gringo/chain" 7 | "github.com/dblokhin/gringo/storage" 8 | "os" 9 | ) 10 | 11 | func init() { 12 | // Output to stdout instead of the default stderr 13 | // Can be any io.Writer, see below for File example 14 | logrus.SetOutput(os.Stdout) 15 | 16 | // Only log the warning severity or above. 17 | logrus.SetLevel(logrus.DebugLevel) 18 | } 19 | 20 | func main() { 21 | logrus.Info("Starting") 22 | chain := chain.New(&chain.Testnet1, storage.NewSqlStorage(nil)) 23 | 24 | sync := p2p.NewSyncer([]string{"127.0.0.1:13414"}, chain, nil) 25 | sync.Pool.Run() 26 | } 27 | 28 | -------------------------------------------------------------------------------- /secp256k1zkp/pedersen.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package secp256k1zkp 6 | 7 | import ( 8 | "encoding/hex" 9 | "io" 10 | ) 11 | 12 | type Commitment []byte 13 | 14 | // Bytes implements p2p Message interface 15 | func (c *Commitment) Bytes() []byte { 16 | return *c 17 | } 18 | 19 | // Read implements p2p Message interface 20 | func (c *Commitment) Read(r io.Reader) error { 21 | _, err := io.ReadFull(r, *c) 22 | 23 | return err 24 | } 25 | 26 | // String implements String() interface 27 | func (c Commitment) String() string { 28 | return hex.EncodeToString(c.Bytes()) 29 | } 30 | -------------------------------------------------------------------------------- /chain/storage.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package chain 6 | 7 | import "github.com/dblokhin/gringo/consensus" 8 | 9 | // Storage represents storage methods for backends 10 | // Storage doesnt check consensus rules! 11 | // all errors in storage are fatals 12 | type Storage interface { 13 | // Adding block to storage 14 | AddBlock(block *consensus.Block) 15 | // Del blocks from id and all of child 16 | DelBlock(id consensus.BlockID) 17 | // Returns full block by hash or height (or both) 18 | // if not found return nil 19 | GetBlock(id consensus.BlockID) *consensus.Block 20 | // returns head of blockchain 21 | GetLastBlock() *consensus.Block 22 | // Returns list of blocks from id 23 | From(id consensus.BlockID, limit int) consensus.BlockList 24 | } 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GRINGO 2 | Golang (Go) implementation of full Grin (grin network) node. 3 | 4 | Development status: frozen (highly unstable grin's consensus & protocol). 5 | 6 | 7 | ## The goals 8 | 9 | - Reliable and fast grin-network node 10 | - Deep dive into p2p, blockchain development skills on fav Golang 11 | - Just for fun 12 | 13 | ## The features 14 | 15 | - Full node 16 | - Mining mode (mining pool) 17 | - API for developers 18 | 19 | 20 | ## How to build 21 | ### Requirements 22 | - Golang >= 1.11 23 | 24 | ### Building node 25 | ``` 26 | $ go get github.com/dblokhin/gringo/cmd/node 27 | ``` 28 | Check your `$GOPATH/bin` folder for binary. 29 | 30 | 31 | ## How to contribute 32 | The __Gringo__ project welcomes contributions. Gringo's primary goal is to be a reliable and fast grin-network node. Changes meet the requirements below, will be considered. 33 | 34 | Contribution requirements: 35 | 36 | 1. Tests: All changes must be accompanied by a new (or changed) test, or a sufficient explanation as to why a new (or changed) test is not required. 37 | 2. ... 38 | -------------------------------------------------------------------------------- /p2p/server.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "math/rand" 9 | "time" 10 | ) 11 | 12 | const ( 13 | noncesCap = 100 14 | ) 15 | 16 | type nonceList struct { 17 | idx int 18 | list []uint64 19 | } 20 | 21 | // Init nonce list 22 | func (n *nonceList) Init() { 23 | n.list = make([]uint64, noncesCap) 24 | 25 | for i := 0; i < noncesCap; i++ { 26 | n.list[i] = rand.Uint64() 27 | } 28 | } 29 | 30 | // NextNonce returns next nonce from list 31 | func (n *nonceList) NextNonce() uint64 { 32 | n.idx = (n.idx + 1) % noncesCap 33 | return n.list[n.idx] 34 | } 35 | 36 | func (n *nonceList) Consist(nonce uint64) bool { 37 | for _, v := range n.list { 38 | if nonce == v { 39 | return true 40 | } 41 | } 42 | 43 | return false 44 | } 45 | 46 | var serverNonces nonceList 47 | 48 | func init() { 49 | // init rand 50 | rand.Seed(time.Now().UnixNano()) 51 | 52 | // init nonce 53 | serverNonces.Init() 54 | } 55 | -------------------------------------------------------------------------------- /p2p/message_test.go: -------------------------------------------------------------------------------- 1 | package p2p 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "github.com/dblokhin/gringo/consensus" 7 | "testing" 8 | ) 9 | 10 | // TestShakeParsing ensures a shake message is parsed correctly. 11 | func TestShakeParsing(t *testing.T) { 12 | message, _ := hex.DecodeString("543402000000000000004500000001000000060000000000007530000000000000000d4d572f4772696e20302e332e30006642e037a073b89c00f48c93cf1b701b335dab84b538136f63b6feadaa50d6") 13 | 14 | sh := new(shake) 15 | read, err := ReadMessage(bytes.NewReader(message), sh) 16 | if err != nil { 17 | t.Errorf("ReadMessage failed") 18 | } 19 | 20 | if read != uint64(len(message)) { 21 | t.Errorf("Failed to consume entire message: read %d of %d", read, len(message)) 22 | } 23 | 24 | if sh.Version != 1 { 25 | t.Errorf("Version differs") 26 | } 27 | 28 | if sh.Capabilities != consensus.CapFastSyncNode { 29 | t.Errorf("Capabilities differs got %d", sh.Capabilities) 30 | } 31 | 32 | if sh.TotalDifficulty != 30000 { 33 | t.Errorf("TotalDifficulty differs") 34 | } 35 | 36 | if sh.UserAgent != "MW/Grin 0.3.0" { 37 | t.Errorf("Version differs") 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /consensus/consensus_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/hex" 10 | "testing" 11 | ) 12 | 13 | func TestHash_ShortID(t *testing.T) { 14 | var hash Hash 15 | var expected ShortID 16 | otherHash := make(Hash, BlockHashSize) 17 | 18 | hash, _ = hex.DecodeString("81e47a19e6b29b0a65b9591762ce5143ed30d0261e5d24a3201752506b20f15c") 19 | expected, _ = hex.DecodeString("e973960ba690") 20 | 21 | if bytes.Compare(hash.ShortID(otherHash), expected) != 0 { 22 | t.Errorf("ShortID was incorrect, want: %s", expected.String()) 23 | } 24 | 25 | hash, _ = hex.DecodeString("3a42e66e46dd7633b57d1f921780a1ac715e6b93c19ee52ab714178eb3a9f673") 26 | expected, _ = hex.DecodeString("f0c06e838e59") 27 | 28 | if bytes.Compare(hash.ShortID(otherHash), expected) != 0 { 29 | t.Errorf("ShortID was incorrect, want: %s", expected.String()) 30 | } 31 | 32 | hash, _ = hex.DecodeString("3a42e66e46dd7633b57d1f921780a1ac715e6b93c19ee52ab714178eb3a9f673") 33 | expected, _ = hex.DecodeString("95bf0ca12d5b") 34 | otherHash, _ = hex.DecodeString("81e47a19e6b29b0a65b9591762ce5143ed30d0261e5d24a3201752506b20f15c") 35 | 36 | if bytes.Compare(hash.ShortID(otherHash), expected) != 0 { 37 | t.Errorf("ShortID was incorrect, got: %s", hash.ShortID(otherHash).String()) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /storage/mysql.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | // sql storage backend 6 | // all errors in storage are fatals 7 | package storage 8 | 9 | import ( 10 | "database/sql" 11 | "github.com/dblokhin/gringo/consensus" 12 | _ "github.com/go-sql-driver/mysql" 13 | "sync" 14 | ) 15 | 16 | // NewSqlStorage returns blockchain Storage defined in /src/chain 17 | func NewSqlStorage(db *sql.DB) *SqlStorage { 18 | return &SqlStorage{ 19 | db: db, 20 | } 21 | } 22 | 23 | // SqlStorage sql storage backend for blockchain 24 | type SqlStorage struct { 25 | sync.RWMutex 26 | 27 | // database instance 28 | db *sql.DB 29 | } 30 | 31 | // AddBlock adds block to storage 32 | func (s *SqlStorage) AddBlock(block *consensus.Block) { 33 | 34 | } 35 | 36 | // DelBlock deletes blocks from id and all of child 37 | func (s *SqlStorage) DelBlock(id consensus.BlockID) { 38 | 39 | } 40 | 41 | // GetBlock returns full block by hash or height (or both) 42 | // if not found return nil 43 | func (s *SqlStorage) GetBlock(id consensus.BlockID) *consensus.Block { 44 | return nil 45 | } 46 | 47 | // Returns list of blocks from id 48 | func (s *SqlStorage) From(id consensus.BlockID, limit int) consensus.BlockList { 49 | return nil 50 | } 51 | 52 | // GetLastBlock returns head of blockchain 53 | func (s *SqlStorage) GetLastBlock() *consensus.Block { 54 | return nil 55 | } 56 | -------------------------------------------------------------------------------- /consensus/locator.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "github.com/sirupsen/logrus" 12 | "io" 13 | ) 14 | 15 | type Locator struct { 16 | Hashes []Hash 17 | } 18 | 19 | // Bytes implements Message interface 20 | func (h *Locator) Bytes() []byte { 21 | buff := new(bytes.Buffer) 22 | 23 | // check the bounds & set the limits 24 | if len(h.Hashes) > MaxLocators { 25 | logrus.Fatal(errors.New("invalid hashes len in locator")) 26 | } 27 | 28 | if err := binary.Write(buff, binary.BigEndian, uint8(len(h.Hashes))); err != nil { 29 | logrus.Fatal(err) 30 | } 31 | 32 | for _, hash := range h.Hashes { 33 | if _, err := buff.Write(hash); err != nil { 34 | logrus.Fatal(err) 35 | } 36 | } 37 | 38 | return buff.Bytes() 39 | } 40 | 41 | // Read implements Message interface 42 | func (h *Locator) Read(r io.Reader) error { 43 | 44 | var count uint8 45 | if err := binary.Read(r, binary.BigEndian, &count); err != nil { 46 | return err 47 | } 48 | 49 | if int(count) > MaxLocators { 50 | return errors.New("too big locator len from peer") 51 | } 52 | 53 | h.Hashes = make([]Hash, count) 54 | for i := 0; i < int(count); i++ { 55 | h.Hashes[i] = make([]byte, BlockHashSize) 56 | 57 | if _, err := io.ReadFull(r, h.Hashes[i]); err != nil { 58 | return err 59 | } 60 | } 61 | 62 | return nil 63 | } 64 | -------------------------------------------------------------------------------- /secp256k1zkp/schnorr_test.go: -------------------------------------------------------------------------------- 1 | package secp256k1zkp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | . "github.com/yoss22/bulletproofs" 7 | "math/big" 8 | "testing" 9 | ) 10 | 11 | func decompressPointFromHex(s string) *Point { 12 | point := new(Point) 13 | b, _ := hex.DecodeString(s) 14 | if err := point.Read(bytes.NewReader(b)); err != nil { 15 | panic(err) 16 | } 17 | return point 18 | } 19 | 20 | func DecodeHex64(s string) [64]byte { 21 | slice, _ := hex.DecodeString(s) 22 | var arr [64]byte 23 | copy(arr[:], slice) 24 | return arr 25 | } 26 | 27 | func TestVerifySignature(t *testing.T) { 28 | // Private key 29 | x := big.NewInt(8) 30 | 31 | // Public key for x. 32 | P := ScalarMulPoint(&G, x) 33 | 34 | msg := [32]byte{} 35 | 36 | // Create a signature for msg using the private key x. 37 | sig := SignMessage(*P, *x, msg) 38 | 39 | // Verify that msg was signed with the private key for P. 40 | if !VerifySignature(*P, msg, sig) { 41 | t.Errorf("failed to verify signature") 42 | } 43 | } 44 | 45 | func TestVerifyKernel(t *testing.T) { 46 | excess := decompressPointFromHex("092095ceab2c20f9a6109a7b0add8d488b3838dcc007c77a43cbe99a14a81b62e8") 47 | signature := DecodeHex64("804b2ed798221e8f4c139daeedeab487221be33db1adf9e129928564e1702b02fbbacaf4cbe4c4b122a9b39d2a7625b9254e43eeade171e9ccafda6dd8538acc") 48 | 49 | fee := uint64(2) 50 | lockHeight := uint64(0) 51 | 52 | msg := ComputeMessage(fee, lockHeight) 53 | 54 | sig := DecodeSignature(signature) 55 | 56 | if !VerifySignature(*excess, msg, sig) { 57 | t.Errorf("verify failed") 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /consensus/id.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "encoding/hex" 11 | "fmt" 12 | "github.com/dchest/siphash" 13 | ) 14 | 15 | const ( 16 | // The size of a short id used to identify inputs|outputs|kernels (6 bytes) 17 | ShortIDSize = 6 18 | ) 19 | 20 | // Hash is hashes (block hash, commitments and so on) 21 | type Hash []byte 22 | 23 | // String prints the hexadecimal encoding of the hash. 24 | func (h Hash) String() string { 25 | return fmt.Sprintf("%032x", []byte(h)) 26 | } 27 | 28 | // ShortID returns shortID from Hash 29 | func (h Hash) ShortID(blockHash Hash) ShortID { 30 | result := make(ShortID, ShortIDSize+2) 31 | 32 | k0 := binary.LittleEndian.Uint64(blockHash[:8]) 33 | k1 := binary.LittleEndian.Uint64(blockHash[8:16]) 34 | 35 | hash := siphash.Hash(k0, k1, h) 36 | binary.LittleEndian.PutUint64(result, hash) 37 | 38 | // returned size is ShortIDSize 39 | return result[0:6] 40 | } 41 | 42 | type ShortID []byte 43 | 44 | // String returns string representation 45 | func (id ShortID) String() string { 46 | return hex.EncodeToString(id) 47 | } 48 | 49 | // ShortIDList sortable list of shortID 50 | type ShortIDList []ShortID 51 | 52 | func (s ShortIDList) Len() int { 53 | return len(s) 54 | } 55 | 56 | func (s ShortIDList) Less(i, j int) bool { 57 | return bytes.Compare(s[i], s[j]) < 0 58 | } 59 | 60 | func (s ShortIDList) Swap(i, j int) { 61 | s[i], s[j] = s[j], s[i] 62 | } 63 | -------------------------------------------------------------------------------- /p2p/protocol.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "bufio" 9 | "errors" 10 | "github.com/dblokhin/gringo/consensus" 11 | "io" 12 | ) 13 | 14 | const ( 15 | // userAgent is name of version of the software 16 | userAgent = "gringo v0.0.1" 17 | ) 18 | 19 | // Message defines methods for WriteMessage/ReadMessage functions 20 | type Message interface { 21 | // Read reads from reader and fit self struct 22 | Read(r io.Reader) error 23 | 24 | // Bytes returns binary data of body message 25 | Bytes() []byte 26 | 27 | // Type says whats the message type should use in header 28 | Type() uint8 29 | } 30 | 31 | // WriteMessage writes to wr (net.conn) protocol message 32 | func WriteMessage(w io.Writer, msg Message) (uint64, error) { 33 | data := msg.Bytes() 34 | 35 | header := Header{ 36 | magic: consensus.MagicCode, 37 | Type: msg.Type(), 38 | Len: uint64(len(data)), 39 | } 40 | 41 | // use the buffered writer 42 | wr := bufio.NewWriter(w) 43 | if err := header.Write(wr); err != nil { 44 | return 0, err 45 | } 46 | 47 | n, err := wr.Write(data) 48 | if err != nil { 49 | return uint64(n) + consensus.HeaderLen, err 50 | } 51 | 52 | return uint64(n) + consensus.HeaderLen, wr.Flush() 53 | } 54 | 55 | // ReadMessage reads from r (net.conn) protocol message 56 | func ReadMessage(r io.Reader, msg Message) (uint64, error) { 57 | var header Header 58 | 59 | // get the msg header 60 | rh := io.LimitReader(r, int64(consensus.HeaderLen)) 61 | if err := header.Read(rh); err != nil { 62 | return 0, err 63 | } 64 | 65 | if header.Type != msg.Type() { 66 | return uint64(consensus.HeaderLen), errors.New("receive unexpected message type") 67 | } 68 | 69 | if header.Len > consensus.MaxMsgLen { 70 | return uint64(consensus.HeaderLen), errors.New("too big message size") 71 | } 72 | 73 | rb := io.LimitReader(r, int64(header.Len)) 74 | return uint64(consensus.HeaderLen) + uint64(header.Len), msg.Read(rb) 75 | } 76 | -------------------------------------------------------------------------------- /p2p/helpers.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "encoding/binary" 9 | "fmt" 10 | "github.com/sirupsen/logrus" 11 | "io" 12 | "net" 13 | ) 14 | 15 | // serializeTCPAddr helps to serialize net.TCPAddr 16 | func serializeTCPAddr(buff io.Writer, addr *net.TCPAddr) { 17 | IP := addr.IP.To4() 18 | if IP == nil { 19 | IP = addr.IP 20 | } 21 | 22 | switch len(IP) { 23 | case net.IPv4len: 24 | { 25 | if _, err := buff.Write([]byte{0}); err != nil { 26 | logrus.Fatal(err) 27 | } 28 | 29 | if _, err := buff.Write(IP); err != nil { 30 | logrus.Fatal(err) 31 | } 32 | } 33 | case net.IPv6len: 34 | { 35 | if _, err := buff.Write([]byte{1}); err != nil { 36 | logrus.Fatal(err) 37 | } 38 | 39 | for i := 0; i < 8; i += 2 { 40 | segment := (uint16(IP[i]) << 8) + uint16(IP[i+1]) 41 | 42 | if err := binary.Write(buff, binary.BigEndian, segment); err != nil { 43 | logrus.Fatal(err) 44 | } 45 | } 46 | } 47 | default: 48 | logrus.Fatal("invalid netaddr") 49 | } 50 | 51 | if err := binary.Write(buff, binary.BigEndian, uint16(addr.Port)); err != nil { 52 | logrus.Fatal(err) 53 | } 54 | } 55 | 56 | // deserializeTCPAddr helps to deserialize net.TCPAddr 57 | func deserializeTCPAddr(r io.Reader) (*net.TCPAddr, error) { 58 | var ipFlag int8 59 | var ipAddr []byte 60 | var ipPort uint16 61 | 62 | if err := binary.Read(r, binary.BigEndian, &ipFlag); err != nil { 63 | return nil, err 64 | } 65 | 66 | switch ipFlag { 67 | case 0: // for ipv4 addr 68 | ipAddr = make([]byte, net.IPv4len) 69 | 70 | if _, err := io.ReadFull(r, ipAddr); err != nil { 71 | return nil, err 72 | } 73 | case 1: // for ipv6 addr 74 | ipAddr = make([]byte, net.IPv6len) 75 | 76 | for i := 0; i < 8; i += 2 { 77 | var segment uint16 78 | 79 | if err := binary.Read(r, binary.BigEndian, segment); err != nil { 80 | return nil, err 81 | } 82 | 83 | ipAddr[i] = byte(segment >> 8) 84 | ipAddr[i+1] = byte(segment) 85 | } 86 | 87 | default: 88 | return nil, fmt.Errorf("invalid ipFlag: %v", ipFlag) 89 | } 90 | 91 | if err := binary.Read(r, binary.BigEndian, &ipPort); err != nil { 92 | return nil, err 93 | } 94 | 95 | return &net.TCPAddr{ 96 | IP: ipAddr, 97 | Port: int(ipPort), 98 | }, nil 99 | } 100 | -------------------------------------------------------------------------------- /cuckoo/siphash24.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package cuckoo 6 | 7 | const ( 8 | siphashBlockBits = uint64(6) 9 | siphashBlockSize = uint64(1 << siphashBlockBits) 10 | siphashBlockMask = uint64(siphashBlockSize - 1) 11 | ) 12 | 13 | // SipHash24 is an implementation of the siphash 2-4 keyed hash function by 14 | // Jean-Philippe Aumasson and Daniel J. Bernstein. 15 | type SipHash24 struct { 16 | // v is the current internal state. 17 | v [4]uint64 18 | } 19 | 20 | // NewSipHash24 returns a new instance of a SipHash24 hasher with the key v. 21 | func NewSipHash24(v [4]uint64) SipHash24 { 22 | return SipHash24{ 23 | v: v, 24 | } 25 | } 26 | 27 | // Sum64 outputs a 64-bit hash. 28 | func (h *SipHash24) Sum64() uint64 { 29 | return h.v[0] ^ h.v[1] ^ h.v[2] ^ h.v[3] 30 | } 31 | 32 | // Write64 computes two, then four rounds of hashing. 33 | func (h *SipHash24) Write64(nonce uint64) { 34 | h.v[3] ^= nonce 35 | 36 | round := func() { 37 | h.v[0] += h.v[1] 38 | h.v[1] = h.v[1]<<13 | h.v[1]>>(64-13) 39 | h.v[1] ^= h.v[0] 40 | h.v[0] = h.v[0]<<32 | h.v[0]>>(64-32) 41 | 42 | h.v[2] += h.v[3] 43 | h.v[3] = h.v[3]<<16 | h.v[3]>>(64-16) 44 | h.v[3] ^= h.v[2] 45 | 46 | h.v[0] += h.v[3] 47 | h.v[3] = h.v[3]<<21 | h.v[3]>>(64-21) 48 | h.v[3] ^= h.v[0] 49 | 50 | h.v[2] += h.v[1] 51 | h.v[1] = h.v[1]<<17 | h.v[1]>>(64-17) 52 | h.v[1] ^= h.v[2] 53 | h.v[2] = h.v[2]<<32 | h.v[2]>>(64-32) 54 | } 55 | 56 | round() 57 | round() 58 | 59 | h.v[0] ^= nonce 60 | h.v[2] ^= 0xff 61 | 62 | round() 63 | round() 64 | round() 65 | round() 66 | } 67 | 68 | // siphash24 computes a single siphash digest using the key v and a nonce. 69 | func siphash24(v [4]uint64, nonce uint64) uint64 { 70 | h := NewSipHash24(v) 71 | h.Write64(nonce) 72 | return h.Sum64() 73 | } 74 | 75 | // siphashBlock computes a block of hashes of size siphashBlockSize. 76 | func siphashBlock(v [4]uint64, nonce uint64) uint64 { 77 | siphash := NewSipHash24(v) 78 | 79 | // Find the start of the block that contains nonce. 80 | start := nonce &^ siphashBlockMask 81 | 82 | // Repeatedly hash from the start of the block to the end. 83 | var nonceHash uint64 84 | for n := start; n < start+siphashBlockSize; n++ { 85 | siphash.Write64(n) 86 | if n == nonce { 87 | nonceHash = siphash.Sum64() 88 | } 89 | } 90 | 91 | // Ensure the whole block of hashes has actually been calculated by xor-ing 92 | // the final state with nonceHash. 93 | if nonce == start+siphashBlockMask { 94 | return siphash.Sum64() 95 | } else { 96 | return nonceHash ^ siphash.Sum64() 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /consensus/network.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | // MagicCode is expected in the header of every message 8 | var MagicCode = [2]byte{0x54, 0x34} 9 | 10 | const ( 11 | // protocolVersion version of grin p2p protocol 12 | ProtocolVersion uint32 = 1 13 | 14 | // size in bytes of a message header 15 | HeaderLen uint64 = 11 16 | 17 | // MaxMsgLen is the maximum size we're willing to accept for any message. Enforced by the 18 | // peer-to-peer networking layer only for DoS protection. 19 | MaxMsgLen uint64 = 20000000 20 | ) 21 | 22 | // Types of p2p messages 23 | const ( 24 | MsgTypeError uint8 = iota 25 | MsgTypeHand 26 | MsgTypeShake 27 | MsgTypePing 28 | MsgTypePong 29 | MsgTypeGetPeerAddrs 30 | MsgTypePeerAddrs 31 | MsgTypeGetHeaders 32 | MsgTypeHeader 33 | MsgTypeHeaders 34 | MsgTypeGetBlock 35 | MsgTypeBlock 36 | MsgTypeGetCompactBlock 37 | MsgTypeCompactBlock 38 | MsgTypeStemTransaction 39 | MsgTypeTransaction 40 | MsgTypeTxHashSetRequest 41 | MsgTypeTxHashSetArchive 42 | MsgTypeBanReason 43 | MsgTypeGetTransaction 44 | MsgTypeTransactionKernel 45 | ) 46 | 47 | // Capabilities of node 48 | type Capabilities uint32 49 | 50 | const ( 51 | // We don't know (yet) what the peer can do. 52 | CapUnknown Capabilities = 0 53 | // Full archival node, has the whole history without any pruning. 54 | CapFullHist = 1 << 0 55 | // Can provide block headers and the UTXO set for some recent-enough height. 56 | CapUtxoHist = 1 << 1 57 | // Can provide a list of healthy peers 58 | CapPeerList = 1 << 2 59 | CapFastSyncNode = CapUtxoHist | CapPeerList 60 | CapFullNode = CapFullHist | CapUtxoHist | CapPeerList 61 | ) 62 | 63 | // Network error codes 64 | const ( 65 | NetUnsupportedVersion int = 100 66 | ) 67 | 68 | const ( 69 | // Maximum number of hashes in a block header locator request 70 | MaxLocators int = 14 71 | 72 | // Maximum number of block headers a peer should ever send 73 | MaxBlockHeaders = 512 74 | 75 | // Maximum number of peer addresses a peer should ever send 76 | MaxPeerAddrs = 256 77 | ) 78 | 79 | // Protocol defines grin-node network communicates 80 | type Protocol interface { 81 | // TransmittedBytes bytes sent and received 82 | // TransmittedBytes() uint64 83 | 84 | // SendPing sends a Ping message to the remote peer. Will panic if handle has never 85 | // been called on this protocol. 86 | SendPing() 87 | 88 | // SendBlock sends a block to our remote peer 89 | SendBlock(block *Block) 90 | 91 | // Relays a transaction to the remote peer 92 | SendTransaction(tx Transaction) 93 | 94 | // Sends a request for block headers based on the provided block locator 95 | SendHeaderRequest(locator Locator) 96 | 97 | // Sends a request for a block from its hash 98 | SendBlockRequest(hash Hash) 99 | 100 | // Sends a request for some peer addresses 101 | SendPeerRequest(capabilities Capabilities) 102 | 103 | // Close the connection to the remote peer 104 | Close() 105 | } 106 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= 2 | github.com/btcsuite/btcd v0.0.0-20181130015935-7d2daa5bfef2 h1:LPHpTTuR7vj3kD7YDRZnrDnFAoj1Ov4cpiO3jN8RnW4= 3 | github.com/btcsuite/btcd v0.0.0-20181130015935-7d2daa5bfef2/go.mod h1:Jr9bmNVGZ7TH2Ux1QuP0ec+yGgh0gE9FIlkzQiI5bR0= 4 | github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= 5 | github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= 6 | github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= 7 | github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= 8 | github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= 9 | github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= 10 | github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= 11 | github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 13 | github.com/dchest/siphash v1.2.1 h1:4cLinnzVJDKxTCl9B01807Yiy+W7ZzVHj/KIroQRvT4= 14 | github.com/dchest/siphash v1.2.1/go.mod h1:q+IRvb2gOSrUnYoPqHiyHXS0FOBBOdl6tONBlVnOnt4= 15 | github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= 16 | github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= 17 | github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 18 | github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= 19 | github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= 20 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 21 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 22 | github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo= 23 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 24 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 25 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 26 | github.com/yoss22/bulletproofs v0.0.0-20181219041900-c29397110419 h1:U0tuxvTQSm5k/zfzm4O1GOS99QcH7mruXFh+Ko7W56o= 27 | github.com/yoss22/bulletproofs v0.0.0-20181219041900-c29397110419/go.mod h1:y8Cc/zNGHI48iP47BwVKFIajpgG5mCKh9OVVZs+G/PM= 28 | golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 29 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 30 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0= 31 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 32 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= 33 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 34 | -------------------------------------------------------------------------------- /secp256k1zkp/constants.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package secp256k1zkp 6 | 7 | import ( 8 | . "github.com/yoss22/bulletproofs" 9 | "math/big" 10 | ) 11 | 12 | const ( 13 | // The size (in bytes) of a message 14 | MessageSize int = 32 15 | 16 | // The size (in bytes) of a secret key 17 | SecretKeySize int = 32 18 | 19 | // The size (in bytes) of a public key array. This only needs to be 65 20 | // but must be 72 for compatibility with the `ArrayVec` library. 21 | PublicKeySize int = 72 22 | 23 | // The size (in bytes) of an uncompressed public key 24 | UncompressedPublicKeySize int = 65 25 | 26 | // The size (in bytes) of a compressed public key 27 | CompressedPublicKeySize int = 33 28 | 29 | // The size (in bytes) of an aggregated signature 30 | AggSignatureSize int = 64 31 | 32 | // The maximum size of a signature 33 | MaxSignatureSize int = 72 34 | 35 | // The maximum size of a compact signature 36 | CompactSignatureSize int = 64 37 | 38 | // The size of a Pedersen commitment 39 | PedersenCommitmentSize int = 33 40 | 41 | // The max size of a range proof 42 | MaxProofSize int = 5134 43 | 44 | // The maximum size of a message embedded in a range proof 45 | // ProofMsgSize int = 4096 46 | ProofMsgSize int = 2048 47 | ) 48 | 49 | var ( 50 | // The order of the secp256k1 curve 51 | CurveOrders = []byte{ 52 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 53 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 54 | 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 55 | 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, 56 | } 57 | 58 | // The X coordinate of the generator 59 | Gx = []byte{ 60 | 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 61 | 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 62 | 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 63 | 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98, 64 | } 65 | 66 | // The Y coordinate of the generator 67 | Gy = []byte{ 68 | 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 69 | 0x5d, 0xa4, 0xfb, 0xfc, 0x0e, 0x11, 0x08, 0xa8, 70 | 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 71 | 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, 0xd4, 0xb8, 72 | } 73 | 74 | // Generator G as a point. 75 | G = Point{ 76 | X: new(big.Int).SetBytes(Gx), 77 | Y: new(big.Int).SetBytes(Gy), 78 | } 79 | 80 | // Generator H 81 | Hx = []byte{ 82 | 0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54, 83 | 0xb7, 0x8b, 0x4b, 0x60, 0x35, 0xe9, 0x7a, 0x5e, 84 | 0x07, 0x8a, 0x5a, 0x0f, 0x28, 0xec, 0x96, 0xd5, 85 | 0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0, 86 | } 87 | Hy = []byte{ 88 | 0x31, 0xd3, 0xc6, 0x86, 0x39, 0x73, 0x92, 0x6e, 89 | 0x04, 0x9e, 0x63, 0x7c, 0xb1, 0xb5, 0xf4, 0x0a, 90 | 0x36, 0xda, 0xc2, 0x8a, 0xf1, 0x76, 0x69, 0x68, 91 | 0xc3, 0x0c, 0x23, 0x13, 0xf3, 0xa3, 0x89, 0x04, 92 | } 93 | 94 | // Generator H as a point. 95 | H = Point{ 96 | X: new(big.Int).SetBytes(Hx), 97 | Y: new(big.Int).SetBytes(Hy), 98 | } 99 | 100 | // Generator J, for switch commitments (as compressed curve point (3)) 101 | GENERATOR_J = []byte{ 102 | 0x11, 103 | 0xb8, 0x60, 0xf5, 0x67, 0x95, 0xfc, 0x03, 0xf3, 104 | 0xc2, 0x16, 0x85, 0x38, 0x3d, 0x1b, 0x5a, 0x2f, 105 | 0x29, 0x54, 0xf4, 0x9b, 0x7e, 0x39, 0x8b, 0x8d, 106 | 0x2a, 0x01, 0x93, 0x93, 0x36, 0x21, 0x15, 0x5f, 107 | } 108 | ) 109 | -------------------------------------------------------------------------------- /consensus/difficulty.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "encoding/binary" 9 | "sort" 10 | "time" 11 | ) 12 | 13 | const ( 14 | ZeroDifficulty Difficulty = 0 15 | 16 | // The minimum mining difficulty we'll allow 17 | MinimumDifficulty Difficulty = 1 18 | ) 19 | 20 | // Difficulty is defined as the maximum target divided by the block hash. 21 | type Difficulty uint64 22 | 23 | func (d Difficulty) FromNum(num uint64) Difficulty { 24 | return Difficulty(num) 25 | } 26 | 27 | // FromHash computes the difficulty from a hash. Divides the maximum target by the 28 | // provided hash. 29 | func (d Difficulty) FromHash(hash Hash) Difficulty { 30 | maxTarget := binary.BigEndian.Uint64(MAXTarget) 31 | 32 | // Use the first 64 bits of the given hash 33 | num := binary.BigEndian.Uint64(hash[:8]) 34 | 35 | return Difficulty(maxTarget / num) 36 | } 37 | 38 | func (d Difficulty) IntoNum() uint64 { 39 | return uint64(d) 40 | } 41 | 42 | // NextDifficulty computes the proof-of-work difficulty that the next block should comply 43 | // with. Takes an iterator over past blocks, from latest (highest height) to 44 | // oldest (lowest height). The iterator produces pairs of timestamp and 45 | // difficulty for each block. 46 | // 47 | // The difficulty calculation is based on both Digishield and GravityWave 48 | // family of difficulty computation, coming to something very close to Zcash. 49 | // The refence difficulty is an average of the difficulty over a window of 50 | // DIFFICULTY_ADJUST_WINDOW blocks. The corresponding timespan is calculated by using the 51 | // difference between the median timestamps at the beginning and the end 52 | // of the window. 53 | 54 | func NextDifficulty(blist BlockList) Difficulty { 55 | 56 | blen := len(blist) 57 | if blen == 0 { 58 | return ZeroDifficulty 59 | } 60 | 61 | // Sum of difficulties in the window, used to calculate the average later. 62 | sumDiff := ZeroDifficulty 63 | 64 | // Block times at the begining and end of the adjustment window, used to 65 | // calculate medians later. 66 | windowBegin := make([]time.Time, 0) 67 | windowEnd := make([]time.Time, 0) 68 | 69 | for i := blen - 1; i >= 0; i-- { 70 | if i < DifficultyAdjustWindow { 71 | sumDiff += blist[i].Header.Difficulty 72 | 73 | if i < MedianTimeWindow { 74 | windowBegin = append(windowBegin, blist[i].Header.Timestamp) 75 | } 76 | } else { 77 | if i < DifficultyAdjustWindow+MedianTimeWindow { 78 | windowEnd = append(windowEnd, blist[i].Header.Timestamp) 79 | } else { 80 | break 81 | } 82 | } 83 | } 84 | 85 | // Check we have enough blocks 86 | if len(windowEnd) < MedianTimeWindow { 87 | return MinimumDifficulty 88 | } 89 | 90 | // Calculating time medians at the beginning and end of the window. 91 | sort.SliceStable(windowBegin, func(i, j int) bool { 92 | return windowBegin[i].Before(windowBegin[j]) 93 | }) 94 | sort.SliceStable(windowEnd, func(i, j int) bool { 95 | return windowEnd[i].Before(windowEnd[j]) 96 | }) 97 | 98 | beginTime := windowBegin[len(windowBegin)/2] 99 | endTime := windowEnd[len(windowEnd)/2] 100 | 101 | // Average difficulty and dampened average time 102 | diffAvg := sumDiff / MinimumDifficulty.FromNum(uint64(DifficultyAdjustWindow)) 103 | ts := (3*BlockTimeWindow + beginTime.Sub(endTime)) / 4 104 | 105 | // Apply time bounds 106 | if ts < LowerTimeBound { 107 | ts = LowerTimeBound 108 | } 109 | if ts > UpperTimeBound { 110 | ts = UpperTimeBound 111 | } 112 | 113 | //Result 114 | diff := diffAvg * MinimumDifficulty.FromNum(uint64(BlockTimeWindow)) / MinimumDifficulty.FromNum(uint64(ts)) 115 | if diff > MinimumDifficulty { 116 | return diff 117 | } 118 | 119 | return MinimumDifficulty 120 | } 121 | -------------------------------------------------------------------------------- /consensus/transaction_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | . "github.com/yoss22/bulletproofs" 7 | "testing" 8 | ) 9 | 10 | func TestTransactionDeserialization(t *testing.T) { 11 | transactionMsg, _ := hex.DecodeString( 12 | "d29efa3aa282679fba8353ac370bc9994394d1b1964fb4830c58bf4a402d4f800000000000000001000000000000000200000000000000010009de9aceb09ff7cc422a3704dddf9373a7bdcc8805b2f81a9ee05786f49238a7660008bc127c31911faf56ed4b3bcc9819dc34b47e104de991ce32519ec333c6638e0600000000000002a34199a825fc69cd4030d11924f3011bba3322fecf866bfd44b05d84ddf4c5fada39284bb90e3594386bb8b116825f90ab2c9ea7e3bbec047a3c0b2586bb58dc520f9687a3f713f6921109ea6474f8219fdbd2aa2b37620b5f2b1da736f6ee43e9d8216ebbc921a8355db6952210d625a89155d60f32ed3deb8dabbc8a8f059bbfa1f1803a367a404121824db8111202311641d61b5c03e0c694b326e4124c3dc9c48a7d9b745bc0e1f1db6cf746d7d183300e3f212d6e4bc4c69b4275644993bd1766d732862ff77ebb1667a8ff9e318338f91cbb0b494e5b934721f24818acfaf27ab2cf5ca78aefa6510bb032666e198000f7b81499fc50fa4ba40b8e866721fa69e08940968769459ae60c22bef2c1ffb6f472243a04ffa049af2cb0ab206349c03cad3c3e40d46f0a5d1999825df1d5af75caa726ec78eb312a716468e8e455071c109a01086c5531fce7d1dad145ceba46a55a32096c23ab867a4842e650f8630027a5206192d55bfae463a340cd95143139af48fa175f158ee0be66715409c1d2db2630a2e85e414cc123bb4a67dfd0b9ea05e22dea7b2fc5f2c28462cb1a74f1e63a513826d9403f38067a68cf5e3172b4023c541d97480ed2421179d7e2abee1d5e11524971adc95682845bea7303427423ec84adf7c4bf99a1f03d6fc02ca6a6328d81c4b23c1c7230a9e0d42b000b885dbd0681ada4ddef22386c97ee1a9dad87c39234ceefc3b5ec41c744f546924a5de250c7f5e1bfe8ee631dc049ec748c0f3702d8b2f2e650af38c5287a64ebe51b43c527978a16226a0eb4b632a11ec51040627e92ce2529c30e3e1b34170d490d5f50abe57fed3e6c2fcde6c39115e002edb5eae0b9a006434ca8e8985e4bf93cb20ee52342b4698865d870258e8ac9a15c55853eabef06f32b12ba28bbec31ecbac8a8bfe12e5c0ccfa21c1a5120000832a3990cd8a497ad280394afeaa5fcbdf02d6e8c86eb7fc47ba6bb25cd8973fd00000000000002a38bfaaaeebbba7ff4b614c75390729666e2ce1cfa0d5fa9d33c7e8327dd468711b1cd2e6a72108735e183ab232114969adf1bda21b78d524ac8d76ab1f68b8c5700c09e2ec7874e6948d6367f8af295b54806dcfe46021ed115f74ba0679509e1b650def8083790f8e26745fa3141d69fd350c7c726bc9453d3e1598cae27f8c131f233de12d947bb4b0c0b0d12fb147d4780eca856b380f9a8a952031e201d12bfc7815082fa7710a0e57feb0a514b8dddcf98c277cc16b6c5347805afc095ad304dbada87330648c6ef0a18f21ad6dde0460c416811f1276e8ea335491b8e297be2f27e8e827f112ef66a3f86e978c39ea770c084d4dbaa96dcfab6966c822a3ef3af42435602689ed3c3b4578097e06a8f609b442ee309a5e5348dcbad74086c9ebb72fa6588db3316dd9e41262cd807b8565d3b1e1a71e7400e90aeffb841ace29355ebd07521672f8b8c1d32f055b8d794bc8ad46150efb595e171cad20f0d0700594fa5d850eb688f4b871c43c8ef039679b2b282ab968a91e4e78d5f223a4acac2484240496912b875c87c5fca8490a78fe78fc18c8f17b87ce8300d8a7360b3e2878302c57747ceb107556640c620c64b196b5a94079b188086d456554fae8cc33e0dab35618e3a4c7645fd16112443f649f2e0b679d63dea8d5da2ed783af2d068b1d830c821af27b954daab77405736258d25c005b9b98634a816d266264d1097824f479ab9addec644e744c579a8b4c0b814ee147a241098de6fb739c88e32828130b62435d7b7836cbd213f7b364e156ee42ed69aa8d83dd5d97af3e4ab2af17e14fab5276bbc0c1243996fed445648a882e5e1a53509ecd5225bbce19f82937ff680f476619242096cff5cf2e19712f62bdeac1488824db6945583bfea1762f26f76dccbd9b1c970e242632480b1abbdb709ce1fbfaf7a092051bdb3dc0000000000007a1200000000000001011908b3e6f62be2a299e1c96627822f1228aeb977a79a7074872e91cb6d0c2f239ab9752e5a56dd5d0d16bfa7c19defe154b1185b3d40acb34d75e73d3de288c5c9dc6326369b0d216ac21ef5e2240f3578e7503aa71a4405ce8f2ee6a0696ed98de7") 13 | 14 | r := bytes.NewReader(transactionMsg) 15 | 16 | tx := &Transaction{} 17 | if err := tx.Read(r); err != nil { 18 | t.Errorf("failed to parse transaction: %v", err) 19 | } 20 | } 21 | 22 | func TestTransactionOutputSerialize(t *testing.T) { 23 | serialized, _ := hex.DecodeString( 24 | "0832a3990cd8a497ad280394afeaa5fcbdf02d6e8c86eb7fc47ba6bb25cd8973fd") 25 | 26 | Commit := new(Point) 27 | if err := Commit.Read(bytes.NewReader(serialized)); err != nil { 28 | t.Errorf("failed to read point") 29 | } 30 | 31 | actual := Commit.Bytes() 32 | if !bytes.Equal(actual, serialized) { 33 | t.Errorf("TestTransactionOutputSerialize wrong, got %x, expected %x", 34 | actual, serialized) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /consensus/proof.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "fmt" 12 | "github.com/dblokhin/gringo/cuckoo" 13 | "github.com/sirupsen/logrus" 14 | "golang.org/x/crypto/blake2b" 15 | "io" 16 | ) 17 | 18 | // RangeProof of work 19 | type Proof struct { 20 | // Power of 2 used for the size of the cuckoo graph 21 | EdgeBits uint8 22 | 23 | // The nonces 24 | Nonces []uint32 25 | } 26 | 27 | var ( 28 | errInvalidPow = errors.New("invalid pow verify") 29 | ) 30 | 31 | // Validate validates the pow 32 | func (p *Proof) Validate(header *BlockHeader, cuckooSize uint8) error { 33 | logrus.Infof("block POW validate for size %d", cuckooSize) 34 | 35 | cuckoo := cuckoo.NewCuckaroo(header.bytesWithoutPOW()) 36 | if cuckoo.Verify(header.POW.Nonces, header.POW.EdgeBits) { 37 | return nil 38 | } 39 | 40 | return errInvalidPow 41 | } 42 | 43 | // ToDifficulty converts the proof to a proof-of-work Target so they can be compared. 44 | // Hashes the Cuckoo Proof data. 45 | func (p *Proof) ToDifficulty() Difficulty { 46 | return MinimumDifficulty.FromHash(p.Hash()) 47 | } 48 | 49 | // Hash returns hash of content pow 50 | func (p *Proof) Hash() []byte { 51 | hash := blake2b.Sum256(p.Bytes()) 52 | return hash[:] 53 | } 54 | 55 | // ProofBytes returns the serialised proof of work nonces. 56 | func (p *Proof) ProofBytes() []byte { 57 | buff := new(bytes.Buffer) 58 | 59 | // The solution we serialise depends on the size of the cuckoo graph. The 60 | // cycle is always of length 42, but each vertex takes up more bits on 61 | // larger graphs, nonceLengthBits is this number of bits. 62 | nonceLengthBits := uint(p.EdgeBits) 63 | 64 | // Make a slice just large enough to fit all of the POW bits. 65 | bitvecLengthBits := nonceLengthBits * uint(ProofSize) 66 | bitvec := make([]uint8, (bitvecLengthBits+7)/8) 67 | 68 | for n, nonce := range p.Nonces { 69 | // Pack this nonce into the bit stream. 70 | for bit := uint(0); bit < nonceLengthBits; bit++ { 71 | // If this bit is set, then write it to the correct position in the 72 | // stream. 73 | if nonce&(1< 64 { 108 | return fmt.Errorf("invalid cuckoo graph size: %d", p.EdgeBits) 109 | } 110 | 111 | p.Nonces = make([]uint32, ProofSize) 112 | 113 | nonceLengthBits := uint(p.EdgeBits) 114 | 115 | // Make a slice just large enough to fit all of the POW bits. 116 | bitvecLengthBits := nonceLengthBits * uint(ProofSize) 117 | bitvec := make([]uint8, (bitvecLengthBits+7)/8) 118 | if _, err := io.ReadFull(r, bitvec); err != nil { 119 | return err 120 | } 121 | 122 | for i := 0; i < ProofSize; i++ { 123 | var nonce uint32 124 | 125 | // Read this nonce from the packed bitstream. 126 | for bit := uint(0); bit < nonceLengthBits; bit++ { 127 | // Find the position of this bit in bitvec 128 | offsetBits := uint(i)*nonceLengthBits + bit 129 | // If this bit is set in bitvec then set the same bit in the nonce. 130 | if bitvec[offsetBits/8]&(1<<(offsetBits%8)) != 0 { 131 | nonce |= 1 << bit 132 | } 133 | } 134 | 135 | p.Nonces[i] = nonce 136 | } 137 | 138 | return nil 139 | } 140 | 141 | func NewProof(nonces []uint32) Proof { 142 | return Proof{ 143 | Nonces: nonces, 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /consensus/transaction.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "fmt" 12 | "github.com/sirupsen/logrus" 13 | "io" 14 | "sort" 15 | ) 16 | 17 | // Transaction an grin transaction 18 | type Transaction struct { 19 | // The "k2" kernel offset. 20 | KernelOffset [32]byte 21 | // Set of inputs spent by the transaction 22 | Inputs InputList 23 | // Set of outputs the transaction produces 24 | Outputs OutputList 25 | // The kernels for this transaction 26 | Kernels TxKernelList 27 | } 28 | 29 | // Bytes implements p2p Message interface 30 | func (t *Transaction) Bytes() []byte { 31 | buff := new(bytes.Buffer) 32 | 33 | if _, err := buff.Write(t.KernelOffset[:]); err != nil { 34 | logrus.Fatal(err) 35 | } 36 | 37 | // Inputs & outputs lens 38 | if err := binary.Write(buff, binary.BigEndian, uint64(len(t.Inputs))); err != nil { 39 | logrus.Fatal(err) 40 | } 41 | 42 | if err := binary.Write(buff, binary.BigEndian, uint64(len(t.Outputs))); err != nil { 43 | logrus.Fatal(err) 44 | } 45 | 46 | if err := binary.Write(buff, binary.BigEndian, uint64(len(t.Kernels))); err != nil { 47 | logrus.Fatal(err) 48 | } 49 | 50 | // Consensus rule that everything is sorted in lexicographical order on the wire 51 | // consensus rule: input, output, kernels MUST BE sorted! 52 | sort.Sort(t.Inputs) 53 | sort.Sort(t.Outputs) 54 | sort.Sort(t.Kernels) 55 | 56 | // Write inputs 57 | for _, input := range t.Inputs { 58 | if _, err := buff.Write(input.Commit); err != nil { 59 | logrus.Fatal(err) 60 | } 61 | } 62 | 63 | // Write outputs 64 | for _, output := range t.Outputs { 65 | if _, err := buff.Write(output.Bytes()); err != nil { 66 | logrus.Fatal(err) 67 | } 68 | } 69 | 70 | // Write kernels 71 | for _, kernel := range t.Kernels { 72 | if _, err := buff.Write(kernel.Bytes()); err != nil { 73 | logrus.Fatal(err) 74 | } 75 | } 76 | 77 | return buff.Bytes() 78 | } 79 | 80 | // Type implements p2p Message interface 81 | func (t *Transaction) Type() uint8 { 82 | return MsgTypeTransaction 83 | } 84 | 85 | // Read implements p2p Message interface 86 | func (t *Transaction) Read(r io.Reader) error { 87 | if _, err := io.ReadFull(r, t.KernelOffset[:]); err != nil { 88 | return err 89 | } 90 | 91 | // Read the lengths of the subsequent fields. 92 | var inputs, outputs, kernels uint64 93 | if err := binary.Read(r, binary.BigEndian, &inputs); err != nil { 94 | return err 95 | } 96 | 97 | if err := binary.Read(r, binary.BigEndian, &outputs); err != nil { 98 | return err 99 | } 100 | 101 | if err := binary.Read(r, binary.BigEndian, &kernels); err != nil { 102 | return err 103 | } 104 | 105 | // Sanity check the lengths. 106 | if inputs > 1000000 { 107 | return errors.New("transaction contains too many inputs") 108 | } 109 | if outputs > 1000000 { 110 | return errors.New("transaction contains too many outputs") 111 | } 112 | if kernels > 1000000 { 113 | return errors.New("transaction contains too many kernels") 114 | } 115 | 116 | t.Inputs = make([]Input, inputs) 117 | for i := uint64(0); i < inputs; i++ { 118 | if err := t.Inputs[i].Read(r); err != nil { 119 | return err 120 | } 121 | } 122 | 123 | t.Outputs = make([]Output, outputs) 124 | for i := uint64(0); i < outputs; i++ { 125 | if err := t.Outputs[i].Read(r); err != nil { 126 | return err 127 | } 128 | } 129 | 130 | t.Kernels = make([]TxKernel, kernels) 131 | for i := uint64(0); i < kernels; i++ { 132 | if err := t.Kernels[i].Read(r); err != nil { 133 | return err 134 | } 135 | } 136 | 137 | // TODO: Check block weight. 138 | 139 | // Check sorted input, output requiring consensus rule! 140 | if !sort.IsSorted(t.Inputs) { 141 | return errors.New("consensus error: inputs are not sorted") 142 | } 143 | 144 | if !sort.IsSorted(t.Outputs) { 145 | return errors.New("consensus error: outputs are not sorted") 146 | } 147 | 148 | if !sort.IsSorted(t.Kernels) { 149 | return errors.New("consensus error: kernels are not sorted") 150 | } 151 | 152 | return nil 153 | } 154 | 155 | // String implements String() interface 156 | func (t Transaction) String() string { 157 | return fmt.Sprintf("%#v", t) 158 | } 159 | -------------------------------------------------------------------------------- /cuckoo/cuckoo_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package cuckoo 6 | 7 | import ( 8 | "testing" 9 | ) 10 | 11 | func TestSum(t *testing.T) { 12 | if siphash24([4]uint64{1, 2, 3, 4}, 10) != uint64(928382149599306901) { 13 | t.Errorf("siphash24 was incorrect, want: %d.", uint64(928382149599306901)) 14 | } 15 | if siphash24([4]uint64{1, 2, 3, 4}, 111) != uint64(10524991083049122233) { 16 | t.Errorf("siphash24 was incorrect, want: %d.", uint64(10524991083049122233)) 17 | } 18 | if siphash24([4]uint64{9, 7, 6, 7}, 12) != uint64(1305683875471634734) { 19 | t.Errorf("siphash24 was incorrect, want: %d.", uint64(1305683875471634734)) 20 | } 21 | if siphash24([4]uint64{9, 7, 6, 7}, 10) != uint64(11589833042187638814) { 22 | t.Errorf("siphash24 was incorrect, want: %d.", uint64(11589833042187638814)) 23 | } 24 | } 25 | 26 | func TestBlock(t *testing.T) { 27 | if siphashBlock([4]uint64{1, 2, 3, 4}, 10) != uint64(1182162244994096396) { 28 | t.Errorf("siphashBlock was incorrect, want: %d.", uint64(1182162244994096396)) 29 | } 30 | if siphashBlock([4]uint64{1, 2, 3, 4}, 123) != uint64(11303676240481718781) { 31 | t.Errorf("siphashBlock was incorrect, want: %d.", uint64(11303676240481718781)) 32 | } 33 | if siphashBlock([4]uint64{9, 7, 6, 7}, 12) != uint64(4886136884237259030) { 34 | t.Errorf("siphashBlock was incorrect, want: %d.", uint64(4886136884237259030)) 35 | } 36 | } 37 | 38 | var V1 = []uint32{ 39 | 0x3bbd, 0x4e96, 0x1013b, 0x1172b, 0x1371b, 0x13e6a, 0x1aaa6, 0x1b575, 40 | 0x1e237, 0x1ee88, 0x22f94, 0x24223, 0x25b4f, 0x2e9f3, 0x33b49, 0x34063, 41 | 0x3454a, 0x3c081, 0x3d08e, 0x3d863, 0x4285a, 0x42f22, 0x43122, 0x4b853, 42 | 0x4cd0c, 0x4f280, 0x557d5, 0x562cf, 0x58e59, 0x59a62, 0x5b568, 0x644b9, 43 | 0x657e9, 0x66337, 0x6821c, 0x7866f, 0x7e14b, 0x7ec7c, 0x7eed7, 0x80643, 44 | 0x8628c, 0x8949e, 45 | } 46 | 47 | func TestValidSolution(t *testing.T) { 48 | header := []byte{49} 49 | cuckoo := New(header, 20) 50 | if !cuckoo.Verify(V1, 75) { 51 | t.Error("Verify failed") 52 | } 53 | } 54 | 55 | func TestValidSolutionCuckaroo(t *testing.T) { 56 | key := [4]uint64{ 57 | 0x23796193872092ea, 58 | 0xf1017d8a68c4b745, 59 | 0xd312bd53d2cd307b, 60 | 0x840acce5833ddc52, 61 | } 62 | expected := []uint32{ 63 | 0x45e9, 0x6a59, 0xf1ad, 0x10ef7, 0x129e8, 0x13e58, 0x17936, 0x19f7f, 0x208df, 0x23704, 64 | 0x24564, 0x27e64, 0x2b828, 0x2bb41, 0x2ffc0, 0x304c5, 0x31f2a, 0x347de, 0x39686, 0x3ab6c, 65 | 0x429ad, 0x45254, 0x49200, 0x4f8f8, 0x5697f, 0x57ad1, 0x5dd47, 0x607f8, 0x66199, 0x686c7, 66 | 0x6d5f3, 0x6da7a, 0x6dbdf, 0x6f6bf, 0x6ffbb, 0x7580e, 0x78594, 0x785ac, 0x78b1d, 0x7b80d, 67 | 0x7c11c, 0x7da35, 68 | } 69 | 70 | cuckoo := NewFromKeys(key) 71 | if !cuckoo.Verify(expected, 19) { 72 | t.Error("Verify failed") 73 | } 74 | } 75 | 76 | func TestShouldFindCycle(t *testing.T) { 77 | // Construct the example graph in figure 1 of the cuckoo cycle paper. The 78 | // cycle is: 8 -> 9 -> 4 -> 13 -> 10 -> 5 -> 8. 79 | 80 | edges := make([]*Edge, 6) 81 | edges[0] = &Edge{U: 8, V: 5} 82 | edges[1] = &Edge{U: 10, V: 5} 83 | edges[2] = &Edge{U: 4, V: 9} 84 | edges[3] = &Edge{U: 4, V: 13} 85 | edges[4] = &Edge{U: 8, V: 9} 86 | edges[5] = &Edge{U: 10, V: 13} 87 | 88 | if findCycleLength(edges) != 6 { 89 | t.Error("Verify failed") 90 | } 91 | } 92 | 93 | func TestShouldNotFindCycle(t *testing.T) { 94 | // Construct a path that isn't closed 95 | // 2 -> 5 -> 4 -> 9 -> 8 -> 11 -> 10 96 | 97 | edges := make([]*Edge, 6) 98 | edges[0] = &Edge{U: 1, V: 5} 99 | edges[1] = &Edge{U: 5, V: 4} 100 | edges[2] = &Edge{U: 4, V: 9} 101 | edges[3] = &Edge{U: 9, V: 8} 102 | edges[4] = &Edge{U: 8, V: 11} 103 | edges[5] = &Edge{U: 11, V: 10} 104 | 105 | cycle := findCycleLength(edges) 106 | if cycle != 0 { 107 | t.Errorf("Verify failed, found unexpected %d-cycle", cycle) 108 | } 109 | } 110 | 111 | func TestShouldNotFindCycleNotBipartite(t *testing.T) { 112 | // Construct a length 3 cycle that implies a non-bipartite graph. 113 | // 2 -> 4 -> 5 -> 2 114 | 115 | edges := make([]*Edge, 3) 116 | edges[0] = &Edge{U: 2, V: 4} 117 | edges[1] = &Edge{U: 4, V: 5} 118 | edges[2] = &Edge{U: 5, V: 2} 119 | 120 | cycle := findCycleLength(edges) 121 | if cycle != 0 { 122 | t.Errorf("Verify failed, found unexpected %d-cycle", cycle) 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /consensus/consensus.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Dmitriy Blokhin. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import "time" 8 | 9 | // Consensus rule that everything is sorted in lexicographical order on the wire. 10 | 11 | // MAXTarget The target is the 32-bytes hash block hashes must be lower than. 12 | var MAXTarget = []byte{0xf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} 13 | 14 | const ( 15 | // BlockHashSize size of block hash 16 | BlockHashSize = 32 17 | 18 | // GrinBase A grin is divisible to 10^9, following the SI prefixes 19 | GrinBase uint64 = 1E9 20 | 21 | // Milligrin, a thousand of a grin 22 | MillGrin uint64 = GrinBase / 1000 23 | 24 | // Microgrin, a thousand of a milligrin 25 | MicroGrin uint64 = MillGrin / 1000 26 | 27 | // Nanogrin, smallest unit, takes a billion to make a grin 28 | NanoGrin uint64 = 1 29 | 30 | // Reward The block subsidy amount 31 | Reward uint64 = 60 * GrinBase 32 | 33 | // CoinbaseMaturity Number of blocks before a coinbase matures and can be spent 34 | CoinbaseMaturity uint64 = 1000 35 | 36 | // MaxBlockCoinbaseOutputs number of max coinbase outputs in a valid block. 37 | // This is to prevent a miner generating an excessively large "compact block". 38 | // But we do techincally support blocks with multiple coinbase outputs/kernels. 39 | MaxBlockCoinbaseOutputs int = 1 40 | 41 | // MaxBlockCoinbaseKernels number of max coinbase kernels in a valid block. 42 | // This is to prevent a miner generating an excessively large "compact block". 43 | // But we do techincally support blocks with multiple coinbase outputs/kernels. 44 | MaxBlockCoinbaseKernels int = 1 45 | 46 | // BlockTimeSec Block interval, in seconds, the network will tune its next_target for. Note 47 | // that we may reduce this value in the future as we get more data on mining 48 | // with Cuckoo Cycle, networks improve and block propagation is optimized 49 | // (adjusting the reward accordingly). 50 | BlockTimeSec time.Duration = 60 51 | 52 | // ProofSize Cuckoo-cycle proof size (cycle length) 53 | ProofSize int = 42 54 | 55 | // DefaultMinEdgeBits is the default Cuckatoo Cycle size used for mining and 56 | // validating. 57 | DefaultMinEdgeBits uint8 = 30 58 | 59 | /// Secondary proof-of-work size, meant to be ASIC resistant. 60 | SecondPowEdgeBits uint8 = 29 61 | 62 | BaseEdgeBits uint8 = 24 63 | 64 | // Easiness Default Cuckoo Cycle easiness, high enough to have good likeliness to find 65 | // a solution. 66 | Easiness uint64 = 50 67 | 68 | // Default number of blocks in the past when cross-block cut-through will start 69 | // happening. Needs to be long enough to not overlap with a long reorg. 70 | // Rational 71 | // behind the value is the longest bitcoin fork was about 30 blocks, so 5h. We 72 | // add an order of magnitude to be safe and round to 48h of blocks to make it 73 | // easier to reason about. 74 | // TODO: check that on bug with size BlockTimeSec 75 | CutThroughHorizon uint32 = 48 * 3600 / uint32(BlockTimeSec) 76 | 77 | // Weight of an input when counted against the max block weigth capacity 78 | BlockInputWeight uint32 = 1 79 | 80 | // Weight of an output when counted against the max block weight capacity 81 | BlockOutputWeight uint32 = 10 82 | 83 | // Weight of a kernel when counted against the max block weight capacity 84 | BlockKernelWeight uint32 = 2 85 | 86 | // Total maximum block weight 87 | MaxBlockWeight uint32 = 80000 88 | 89 | // Fork every 250,000 blocks for first 2 years, simple number and just a 90 | // little less than 6 months. 91 | HardForkInterval uint64 = 250000 92 | 93 | // The block height at which version 2 blocks are valid 94 | HardForkV2Height uint64 = 95000 95 | 96 | // Time window in blocks to calculate block time median 97 | MedianTimeWindow int = 11 98 | 99 | // Index at half the desired median 100 | MedianTimeIndex = MedianTimeWindow / 2 101 | 102 | // Number of blocks used to calculate difficulty adjustments 103 | DifficultyAdjustWindow int = 60 104 | 105 | // Average time span of the difficulty adjustment window 106 | BlockTimeWindow time.Duration = time.Duration(DifficultyAdjustWindow) * BlockTimeSec 107 | 108 | // Maximum size time window used for difficulty adjustments 109 | UpperTimeBound time.Duration = BlockTimeWindow * 2 110 | 111 | // Minimum size time window used for difficulty adjustments 112 | LowerTimeBound time.Duration = BlockTimeWindow * 2 113 | ) 114 | -------------------------------------------------------------------------------- /secp256k1zkp/schnorr.go: -------------------------------------------------------------------------------- 1 | package secp256k1zkp 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/sha256" 6 | "encoding/binary" 7 | "github.com/btcsuite/btcd/btcec" 8 | . "github.com/yoss22/bulletproofs" 9 | "math/big" 10 | ) 11 | 12 | const ( 13 | // TagPubkeyEven is prepended to a compressed pubkey to signal that the y 14 | // coordinate is even. 15 | TagPubkeyEven = 0x02 16 | 17 | // TagPubkeyOdd is prepended to a compressed pubkey to signal that the y 18 | // coordinate is odd. 19 | TagPubkeyOdd = 0x03 20 | ) 21 | 22 | // RandomBytes returns 32 bytes of randomness. 23 | func RandomBytes() [32]byte { 24 | buf := [32]byte{} 25 | _, err := rand.Read(buf[:]) 26 | if err != nil { 27 | panic("Unable to generate random int") 28 | } 29 | 30 | return buf 31 | } 32 | 33 | // RandomInt returns a scalar from Z_n. 34 | func RandomInt() *big.Int { 35 | retry: 36 | buf := RandomBytes() 37 | 38 | r := &big.Int{} 39 | r.SetBytes(buf[:]) 40 | 41 | if r.Cmp(btcec.S256().N) == 1 { 42 | goto retry 43 | } 44 | 45 | return r 46 | } 47 | 48 | // Signature is an argument of knowledge that the signer possesses a private 49 | // key. 50 | type Signature struct { 51 | S big.Int 52 | R Point 53 | } 54 | 55 | // Bytes serializes the signature. 56 | func (s Signature) Bytes() [64]byte { 57 | var buf [64]byte 58 | Rx := GetB32(s.R.X) 59 | S := GetB32(&s.S) 60 | copy(buf[0:32], Rx[:]) 61 | copy(buf[32:64], S[:]) 62 | return buf 63 | } 64 | 65 | // SignMessage convinces a verifier in zero knowledge that they know 66 | // the private key x for a public key P = x*G. 67 | // 68 | // The prover sends a random curve point R = k*G which acts as a blinding 69 | // factor. 70 | // The verifier issues a random challenge e. 71 | // The prover returns s = k + ex (i.e. a blinded multiple of x). 72 | // The verifier can now check 73 | // s*G == k*G + (ex)*G 74 | // s*G == R + e*P 75 | func SignMessage(publicKey Point, privateKey big.Int, message [32]byte) Signature { 76 | // Compute a random nonce, k. 77 | k := RandomInt() 78 | 79 | // R is the public key for k. 80 | R := ScalarMulPoint(&G, k) 81 | 82 | // Compute a non-interactive challenge. 83 | Rx := GetB32(R.X) 84 | compressedPubkey := CompressPubkey(publicKey) 85 | challenge := ComputeHash( 86 | Rx[:], 87 | compressedPubkey[:], 88 | message[:]) 89 | e := new(big.Int).SetBytes(challenge[:]) 90 | 91 | s := Sum(k, Mul(e, &privateKey)) 92 | 93 | return Signature{S: *s, R: *R} 94 | } 95 | 96 | // VerifySignature returns true if the given signature was computed by signing 97 | // message with the private key for publicKey. 98 | func VerifySignature(publicKey Point, message [32]byte, signature Signature) bool { 99 | Rx := GetB32(signature.R.X) 100 | compressedPubkey := CompressPubkey(publicKey) 101 | 102 | // Compute the non-interactive challenge. 103 | challenge := ComputeHash( 104 | Rx[:], 105 | compressedPubkey[:], 106 | message[:]) 107 | e := new(big.Int).SetBytes(challenge[:]) 108 | 109 | // Verify s*G == R + e*P. 110 | lhs := ScalarMulPoint(&G, &signature.S) 111 | rhs := SumPoints(&signature.R, ScalarMulPoint(&publicKey, e)) 112 | 113 | return lhs.X.Cmp(rhs.X) == 0 114 | } 115 | 116 | // CommitValue returns the Pedersen commitment to the value v with blinding 117 | // factor blind. 118 | func CommitValue(blind, v *big.Int) *Point { 119 | return SumPoints( 120 | ScalarMulPoint(&G, blind), 121 | ScalarMulPoint(&H, v)) 122 | } 123 | 124 | // CompressPubkey returns the point p as a 33-byte compressed pubkey. 125 | func CompressPubkey(p Point) [33]byte { 126 | var buf [33]byte 127 | if p.Y.Bit(0) == 1 { // is odd 128 | buf[0] = TagPubkeyOdd 129 | } else { 130 | buf[0] = TagPubkeyEven 131 | } 132 | x := GetB32(p.X) 133 | copy(buf[1:33], x[:]) 134 | return buf 135 | } 136 | 137 | // decompressPoint returns the y-coordinate for the given x coordinate. 138 | func decompressPoint(xBytes []byte) *big.Int { 139 | x := new(big.Int).SetBytes(xBytes) 140 | 141 | // Derive the possible y coordinates from the secp256k1 curve 142 | // y² = x³ + 7. 143 | x3 := new(big.Int).Mul(x, x) 144 | x3.Mul(x3, x) 145 | x3.Add(x3, btcec.S256().Params().B) 146 | 147 | // y = ±sqrt(x³ + 7). 148 | y := ModSqrtFast(x3) 149 | 150 | return y 151 | } 152 | 153 | // DecodeSignature reads a 64-byte signature. 154 | func DecodeSignature(signature [64]byte) Signature { 155 | s := new(big.Int).SetBytes(signature[32:64]) 156 | 157 | R := new(Point) 158 | R.X = new(big.Int).SetBytes(signature[0:32]) 159 | R.Y = decompressPoint(signature[0:32]) 160 | 161 | return Signature{ 162 | S: *s, 163 | R: *R, 164 | } 165 | } 166 | 167 | // ComputeHash returns the SHA256 hash of all of the inputs. 168 | func ComputeHash(inputs ...[]byte) [32]byte { 169 | hasher := sha256.New() 170 | 171 | for i := range inputs { 172 | hasher.Write(inputs[i]) 173 | } 174 | 175 | var result [32]byte 176 | copy(result[:], hasher.Sum(nil)) 177 | return result 178 | } 179 | 180 | // ComputeMessage encodes fee and lockHeight into a 32-byte message. 181 | func ComputeMessage(fee, lockHeight uint64) [32]byte { 182 | var msg [32]byte 183 | binary.BigEndian.PutUint64(msg[16:], fee) 184 | binary.BigEndian.PutUint64(msg[24:], lockHeight) 185 | return msg 186 | } 187 | -------------------------------------------------------------------------------- /cuckoo/cuckoo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package cuckoo 6 | 7 | import ( 8 | "encoding/binary" 9 | "github.com/sirupsen/logrus" 10 | "golang.org/x/crypto/blake2b" 11 | ) 12 | 13 | // Edge represents an edge in the cuckoo graph from vertex U to vertex V. 14 | type Edge struct { 15 | U uint64 16 | V uint64 17 | 18 | usedU bool 19 | usedV bool 20 | } 21 | 22 | // findCycleLength attempts to walk the given edges and returns the length of 23 | // the cycle. 24 | func findCycleLength(edges []*Edge) int { 25 | i := 0 // first node 26 | cycle := 0 // the current length of the cycle 27 | 28 | loop: 29 | for { 30 | // If the current cycle length is even we need to look for an edge from 31 | // U -> V. 32 | vertexInUPartition := cycle&1 == 0 33 | 34 | if vertexInUPartition { 35 | // Find an unused edge that connects to the current vertex. 36 | for j := range edges { 37 | if j != i && !edges[j].usedU && edges[i].U == edges[j].U { 38 | edges[i].usedU = true 39 | edges[j].usedU = true 40 | 41 | i = j 42 | cycle++ 43 | 44 | continue loop 45 | } 46 | } 47 | } else { 48 | // Find an unused edge that connects to the current vertex. 49 | for j := range edges { 50 | if j != i && !edges[j].usedV && edges[i].V == edges[j].V { 51 | edges[i].usedV = true 52 | edges[j].usedV = true 53 | 54 | i = j 55 | cycle++ 56 | 57 | continue loop 58 | } 59 | } 60 | } 61 | 62 | // If we didn't find a match for this vertex then we're done. 63 | break 64 | } 65 | 66 | return cycle 67 | } 68 | 69 | // New returns a new instance of a Cuckoo cycle verifier. key is the data used 70 | // to derived the siphash keys from and sizeShift is the number of vertices in 71 | // the cuckoo graph as an exponent of 2. 72 | func New(key []byte, sizeShift uint8) *Cuckoo { 73 | bsum := blake2b.Sum256(key) 74 | key = bsum[:] 75 | 76 | var v [4]uint64 77 | v[0] = binary.LittleEndian.Uint64(key[:8]) 78 | v[1] = binary.LittleEndian.Uint64(key[8:16]) 79 | v[2] = binary.LittleEndian.Uint64(key[16:24]) 80 | v[3] = binary.LittleEndian.Uint64(key[24:32]) 81 | 82 | numVertices := uint64(1) << sizeShift 83 | 84 | return &Cuckoo{ 85 | mask: numVertices/2 - 1, 86 | size: numVertices, 87 | v: v, 88 | } 89 | } 90 | 91 | // Cuckoo cycle context 92 | type Cuckoo struct { 93 | mask uint64 94 | 95 | // size is the number of vertices in the cuckoo graph. 96 | size uint64 97 | 98 | // v is the key for siphash 99 | v [4]uint64 100 | } 101 | 102 | func (c *Cuckoo) newNode(nonce uint64, i uint64) uint64 { 103 | return ((siphash24(c.v, 2*nonce+i) & c.mask) << 1) | i 104 | } 105 | 106 | func (c *Cuckoo) NewEdge(nonce uint32) *Edge { 107 | return &Edge{ 108 | U: c.newNode(uint64(nonce), 0), 109 | V: c.newNode(uint64(nonce), 1), 110 | } 111 | } 112 | 113 | // Verify constructs a cuckoo subgraph from the edges generated by nonces and 114 | // checks whether they form a cycle of the correct length. 115 | func (c *Cuckoo) Verify(nonces []uint32, ease uint64) bool { 116 | proofSize := len(nonces) 117 | 118 | // zero proof is always invalid 119 | if proofSize == 0 { 120 | return false 121 | } 122 | 123 | easiness := ease * c.size / 100 124 | 125 | // Create graph edges from the nonces. 126 | edges := make([]*Edge, proofSize) 127 | for i := 0; i < proofSize; i++ { 128 | // Ensure nonces are in ascending order and that they are all of the 129 | // correct easiness. 130 | if uint64(nonces[i]) >= easiness || (i != 0 && nonces[i] <= nonces[i-1]) { 131 | logrus.Infof("Nonce %d is invalid", i) 132 | return false 133 | } 134 | 135 | edges[i] = c.NewEdge(nonces[i]) 136 | } 137 | 138 | return findCycleLength(edges) == proofSize 139 | } 140 | 141 | // Cuckaroo is the asic-resistant version of the cuckoo-cycle mining algorithm. 142 | type Cuckaroo struct { 143 | // v is the key for siphash 144 | v [4]uint64 145 | } 146 | 147 | // NewCuckaroo returns a new instance of a Cuckaroo cycle verifier. key is the 148 | // data used to derived the siphash keys from and sizeShift is the number of 149 | // vertices in the cuckoo graph as an exponent of 2. 150 | func NewCuckaroo(key []byte) *Cuckaroo { 151 | bsum := blake2b.Sum256(key) 152 | key = bsum[:] 153 | 154 | var v [4]uint64 155 | v[0] = binary.LittleEndian.Uint64(key[:8]) 156 | v[1] = binary.LittleEndian.Uint64(key[8:16]) 157 | v[2] = binary.LittleEndian.Uint64(key[16:24]) 158 | v[3] = binary.LittleEndian.Uint64(key[24:32]) 159 | 160 | return &Cuckaroo{ 161 | v: v, 162 | } 163 | } 164 | 165 | // NewFromKeys returns a new instance of a Cuckaroo verifier with the given key. 166 | func NewFromKeys(keys [4]uint64) *Cuckaroo { 167 | return &Cuckaroo{ 168 | v: keys, 169 | } 170 | } 171 | 172 | // Verify constructs a cuckaroo subgraph from the edges generated by nonces and 173 | // checks whether they form a cycle of the correct length. 174 | func (c *Cuckaroo) Verify(nonces []uint32, edgeBits uint8) bool { 175 | proofSize := len(nonces) 176 | 177 | // zero proof is always invalid 178 | if proofSize == 0 { 179 | return false 180 | } 181 | 182 | numEdges := uint64(1< numEdges || (i != 0 && nonces[i] <= nonces[i-1]) { 190 | logrus.Infof("Nonce %d is invalid", i) 191 | return false 192 | } 193 | 194 | edges[i] = c.NewEdge(nonces[i], numEdges) 195 | } 196 | 197 | return findCycleLength(edges) == proofSize 198 | } 199 | 200 | func (c *Cuckaroo) NewEdge(nonce uint32, mask uint64) *Edge { 201 | e := siphashBlock(c.v, uint64(nonce)) 202 | return &Edge{ 203 | U: e & mask, 204 | V: (e >> 32) & mask, 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /p2p/sync.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "github.com/dblokhin/gringo/consensus" 9 | "github.com/sirupsen/logrus" 10 | ) 11 | 12 | type Blockchain interface { 13 | // Requite a mutex 14 | Lock() 15 | Unlock() 16 | RLock() 17 | RUnlock() 18 | 19 | Genesis() consensus.Block 20 | TotalDifficulty() consensus.Difficulty 21 | Height() uint64 22 | GetBlockHeaders(loc consensus.Locator) []consensus.BlockHeader 23 | GetBlock(hash consensus.Hash) *consensus.Block 24 | 25 | // ProcessHeaders processing block headers 26 | // Validate blockchain rules 27 | // ban peer with consensus error 28 | ProcessHeaders(headers []consensus.BlockHeader) error 29 | 30 | // ProcessBlock processing block 31 | // Validate blockchain rules 32 | // ban peer with consensus error 33 | // update Height & TotalDiff on peer from which recv the block 34 | 35 | // propagate block on new block to connected peer with less Height 36 | // clear tx's from pool on new block 37 | ProcessBlock(block *consensus.Block) error 38 | } 39 | 40 | type Mempool interface { 41 | // ProcessTx processing transaction 42 | // Validate blockchain rules 43 | // ban peer with consensus error 44 | ProcessTx(transaction *consensus.Transaction) error 45 | } 46 | 47 | type PeersPool interface { 48 | // PropagateBlock block to connected peer with less Height 49 | PropagateBlock(block *consensus.Block) 50 | 51 | // Peers returns live peers list (without banned) 52 | Peers(capabilities consensus.Capabilities) *PeerAddrs 53 | 54 | // PeerInfo returns peer structure 55 | PeerInfo(addr string) *peerInfo 56 | 57 | // Add peer 58 | Add(addr string) 59 | 60 | // Ban peer & ensure closed connection 61 | Ban(addr string) 62 | 63 | // Run & stop 64 | Run() 65 | Stop() 66 | } 67 | 68 | // Syncer synchronize blockchain & mempool via peers pool 69 | type Syncer struct { 70 | // Chain is a grin blockchain 71 | Chain Blockchain 72 | Mempool Mempool 73 | 74 | // Pool of peers (peers manager) 75 | Pool PeersPool 76 | } 77 | 78 | // Start starts sync proccess with initial peer addrs 79 | func NewSyncer(addrs []string, chain Blockchain, mempool Mempool) *Syncer { 80 | 81 | sync := new(Syncer) 82 | sync.Chain = chain 83 | sync.Mempool = mempool 84 | sync.Pool = newPeersPool(sync) 85 | 86 | for _, addr := range addrs { 87 | sync.Pool.Add(addr) 88 | } 89 | 90 | return sync 91 | } 92 | 93 | // Run begins syncing with peers. 94 | func (s *Syncer) Run() { 95 | s.Pool.Run() 96 | } 97 | 98 | // Stop stops activity 99 | func (s *Syncer) Stop() { 100 | s.Pool.Stop() 101 | } 102 | 103 | func (s *Syncer) ProcessMessage(peer *Peer, message Message) { 104 | 105 | peerInfo := s.Pool.PeerInfo(peer.Addr) 106 | if peerInfo == nil { 107 | // should never rich 108 | logrus.Fatal("unexpected error") 109 | } 110 | 111 | switch msg := message.(type) { 112 | case *Ping: 113 | // MUST be answered 114 | // update peer info 115 | peerInfo.Lock() 116 | peerInfo.TotalDifficulty = msg.TotalDifficulty 117 | peerInfo.Height = msg.Height 118 | peerInfo.Unlock() 119 | 120 | // send answer 121 | var resp Pong 122 | 123 | // Lock the chain before getting various params 124 | s.Chain.RLock() 125 | resp.TotalDifficulty = s.Chain.TotalDifficulty() 126 | resp.Height = s.Chain.Height() 127 | s.Chain.RUnlock() 128 | 129 | peer.WriteMessage(&resp) 130 | logrus.Debugf("Sent Pong to %s", peer.conn.RemoteAddr()) 131 | 132 | case *Pong: 133 | // update peer info 134 | peerInfo.Lock() 135 | peerInfo.TotalDifficulty = msg.TotalDifficulty 136 | peerInfo.Height = msg.Height 137 | peerInfo.Unlock() 138 | 139 | logrus.Debugf("Received Pong from %s", peer.conn.RemoteAddr()) 140 | 141 | case *GetPeerAddrs: 142 | // MUST NOT be answered 143 | // Send answer 144 | peers := s.Pool.Peers(msg.Capabilities) 145 | if peers != nil { 146 | peer.WriteMessage(peers) 147 | } 148 | logrus.Debugf("Sent %d PeerAddrs to %s", len(peers.peers), peer.conn.RemoteAddr()) 149 | 150 | case *PeerAddrs: 151 | // Adding peer to pool 152 | for _, p := range msg.peers { 153 | s.Pool.Add(p.String()) 154 | } 155 | 156 | case *GetBlockHeaders: 157 | // MUST be answered 158 | // send answer 159 | headers := s.Chain.GetBlockHeaders(msg.Locator) 160 | resp := BlockHeaders{ 161 | Headers: headers, 162 | } 163 | 164 | peer.WriteMessage(&resp) 165 | 166 | case *BlockHeader: 167 | headers := []consensus.BlockHeader{msg.Header} 168 | if err := s.Chain.ProcessHeaders(headers); err != nil { 169 | // ban peer ? 170 | //s.Pool.Ban(peer.conn.RemoteAddr().String()) 171 | logrus.Infof("Failed to process header: %v", err) 172 | } 173 | 174 | logrus.Debugf("Received BlockHeader from %s for height %d: %v:", peer.conn.RemoteAddr(), msg.Header.Height, msg.Header.Hash()) 175 | 176 | case *BlockHeaders: 177 | if err := s.Chain.ProcessHeaders(msg.Headers); err != nil { 178 | // ban peer ? 179 | s.Pool.Ban(peer.conn.RemoteAddr().String()) 180 | } 181 | 182 | case *GetBlock: 183 | // MUST NOT be answered 184 | if block := s.Chain.GetBlock(msg.Hash); block != nil { 185 | peer.WriteMessage(block) 186 | } 187 | 188 | case *consensus.Block: 189 | // ProcessBlock puts block into blockchain 190 | // if block on the top of chain than propagate it 191 | // to others nodes with less TotalDifficulty 192 | if err := s.Chain.ProcessBlock(msg); err != nil { 193 | logrus.Info(err) 194 | // TODO: maybe smarter ban peer ? 195 | s.Pool.Ban(peer.conn.RemoteAddr().String()) 196 | } 197 | 198 | // update peer info 199 | peerInfo.Lock() 200 | 201 | if peerInfo.TotalDifficulty < msg.Header.TotalDifficulty || peerInfo.Height < msg.Header.Height { 202 | peerInfo.TotalDifficulty = msg.Header.TotalDifficulty 203 | peerInfo.Height = msg.Header.Height 204 | } 205 | 206 | peerInfo.Unlock() 207 | 208 | // propagate if it is top block 209 | if msg.Header.Height == s.Chain.Height() { 210 | s.Pool.PropagateBlock(msg) 211 | } 212 | 213 | case *consensus.Transaction: 214 | if err := s.Mempool.ProcessTx(msg); err != nil { 215 | // ban peer ? 216 | s.Pool.Ban(peer.conn.RemoteAddr().String()) 217 | } 218 | 219 | // TODO: propagate tx? 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /consensus/block_test.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "testing" 7 | ) 8 | 9 | var ( 10 | // Testnet4 Block 65,927. 11 | serialisedBlock, _ = hex.DecodeString( 12 | "00010000000000010187000000005c04daea09ff0a5d1c0c9ccef8b8457265655d0ad83cc0674b9aaec959d5987bfec8e0e808971ecd08dfcc1c3fdf79d64e5ed5439cc70b1e3e14f48fbb9acc39f075904ddc6b24e1bb63fd8af854be5f2976f4ab6afe2f38a7af6e54347733e8f18f5571d96490abdb18827c562e08a70a132983daecfe07cb3990c7c7d76f1650d7324946d3a57e8dadc45757b1d3945befb5b894bc50b97e7d94080e6cd1355bcb645b54dfe00b7b7143a3eae538e59e90e921216f762d400ec1913a78045ca7430db40000000000056abf000000000003b5d0000000010a83b80200000bef2ea3e4fb0fbca5ec1d2376ef603e35303c1b07869384e010cc8120404feb073091015943d32e7f511fe6e69c09691292212eb96c55be63bb7e94c799e9da45730df568990fab2df53fc1ed6a6cb822dea607bdb3f9d2d062a162da5aa4ac7d8d2843195209ee71767fb4d2a0d059aae282596ff6972b901fab5db528b6e4257db76e0710f755666226f31d7d9a1aa931790136db95d86e26f6e09cfbfbdca450c50300000000000000010000000000000003000000000000000200097d03927ae0e5dae4ae0c329daa41172410b8213cc8aac5af5ce149cf3ada3f0200081175fcf8c335ff7839d035c9fdecef7f93e2dd0a0a9d08f659cdb61c2e63605800000000000002a3460abccbe856f51f0a4248d8aaa93b171f66b9e51fa75492acb24a436c84baf7e6c23f316124966ed9b36e7ad46f0516c39c4863bf472536df28faff947a3a3e065dcdc47bd1a9ab96bdfdfb9ea8ad25cdd0cab8eee308f90073469c758ad480301764f2109cd6ae0e7584640bd1833eae0507cf04f4c5c0380e1672940bf88b091726c10fee3b9bf217596a20813037d661091c3d89e743ac4ba0c159e4d8aefb35bbd11c46a9291ac5f8f1bd6932eb666f7847ef846a686ea4a0d711b359a2992b57c52e10e88455fd777945394a6de004f336d3b603dcfb2d2e30fea46f6d185ffd21e3d757a26d9d5fd3617f586a2a0ef8a29015c971e67ecdb184c18b6471a08af4de37bc50dd4c2e578354bcd23e1a2cb66b84fb6d4e2aa429a0095306d027ba6ad1e4de3402337182c03adc0d970fa624e866468e4d07081462773002da6ff8c8ece6746f8f65131bdd55309c7b6b204c0d224d70ebdf84a523a32e1fa5250357eaa7554c7d12010218af014f2f2f147ca506747b356c3b83510b9ab394239faa4f9ff1962bc8dd798d6cb1a2c1541bf2acb8134a4354e4814827e7374ac3d909eb8b6b8596462570aa2243364dc657963609fc5cecae625b97bf7533810177a487939b1c928cb7c66ac9a443b8a62b4bcd859ba5b888e069636a349e59d46bc1cc62612bf20fb8153d2c3029e776c21aae62f3e4d07aab6d747bdafca348de971200686c27f72fd405361e47eb3f795d9bba78d96a6b7489a05f1449dcbda37a08d4a8070d0a0381317221161ba0cc57c22819a43d4167da2d6b8f78088bb006ffc88cee29abf41286a20121fe34518692438bd88420f78c500a6927ea2b603bfd30996631b8cf27eeb26459aab2c328dd2eb060672f80ce7ecaab0f569ec1702bd486204529baec0bd7d2eded0ee7f32020217089213b6d2fce379a7315be0108bfd392f055a4870d75b447db31c59daa27eda8471f40dcfcb3a8fa399ae0afe100000000000002a3fd3b70fa382fa153ed195eb2d21fa0a3c275ad16c9aebe32f76f1e3f69e3e934f35bc21360b456da9a982d01b25dfb1868b6154bd4b5eebd1b8d7b907a6ea1510416213cf947b28234130e390c2a4893ac399b36718d3d2ca9d894fb2bb512fa741258da97a1b4697db3a72ab3bb081aa408ae5566c06a3fdecb0281463d329371331d5d7c5bed3a9493f2998314c83f7c7c42ecf2d5d1e1bfefe8987628b7ff0578ce51e718f15639d849423158623bb78e82cf622b10258458342eebf162496d223a1e296753eaeb6d231714455bfd5ee31d574642cb31d25458d8a0ddf4c4ea6aab4ace94a92435fd4e6bebe5f9f5d7bc8e18320d72288297a486586f06c78a00957b34529750cfe4824b79589587f54e9082e88d6e20eec484197cdb8ea418622f27a74489061040a23e5b234a8ac220807bdad3387398417b1e92a6d6ecbbad59967c19f7ec8fb214cb11403b4927c17d2e7367b8354c1dd42a5306c2ab19fd01226fe8cbbccc1ab2054016ba748377f74d9365f40f0b8771f33c5199c492253504cd9e369f456c560ae1958764e71f1e5a7060f072882fb7cc08d1975e4a27350d6a9a2895626fe480d5d7107976ca57fc489f17212cd20ce3041e9bf77c3a15f2ca654c980ee97fb600310caf01091a66db2ef065e89f51b7e3c6670a042ef55e803a1d443e051efc9803f5610dd358beb251aa0edb58133f0a46869b4a08e46d2ae974bfc9e6cdd1e7af6eda4dc9fde07fa0f6a5ace4d8f43bcd019df4939e7d990f4d2828cc83fd0cc47369a13b71e212c142927df67faf280ea071c3043980e3fd1955398aeb1df7f769526dfb3ad4851b94d0e1e3c452b699407fec48d6ac8593b505c774a4f0a60dd63c0aa11cc12c7a201856f80c0423e73aa42dde50502aefb9c0276ecb4508ed6f22927767c791cd4535adabe5b6695076c5ec0aa90008c1806612f951ecc80f7f4e9258b4d089713bd19094cd8829ffe4ba7c02e9e81300000000000002a3f6fff7b0775aca3d2db82e41f28cca051f3a479ec229e1d18445b8fb2c9fb3658b31fb733c7511364210c937a17dffe30850281af266f5cc9f82328a1440c42b0933fc288d720a6a4b60715bca84d36ca3e578ef61ca8cd8444d0289586dc82cd1d55d007f15d1e76a1a6c9287d11f2be6dcc5531e65eabdf63a1463860a694a59a7e48d3ed7c324aaad92f58f11394874b7b9f982af598b70c450c26b978311df16f9586a8d60290017a20b5b3c73028716d450b1767a4d20d76f4cce34ad7d9fe3e983191f3bdf2b40fa8049cc58f8bc27fd389101bb12ded0106556f6a494baf2dbc89910fada29c8faf8bee9ffcff5736085fe37018fe3bd48f5b71f10f47079b2db98b89480dcaa09e85c6aa6ec2ee9ca71b912ecaae2e2700d090905b0e999eea68ed40a9ddbf5c0509c86c122cc4ecfe94b86d705aa463de2ddfddc4083cc731b300a7ebe01fb1a6c42bbd730e21246f6a84aafd1f21d7abd8cb94f4bb37b008919348436d7b9c477694d44c4ffca00c452d2940ed35c1006f9d1b4d583748585525c8febc321ffd75d802bf15772e3458ed478dd08456e3048358eb8740d5260b599a8e7f200e0a3a3136b5f8cf2b286b73eac5c59f0ee52e64483d5ca3a874075098258994fb4d3262483997f0ef8a118445a3f3923dd7805f2d75f4a0163eb9c6871c3ce111b4593d2a9f42817efac9a65c1a1324405307ca25189ec4aee9f5bef1711021cc83a86db752e1f141a0edef9ee3ae04496822a888a9b5cf412225f300eeee906558a40251a96a618cc23d67c48f23d5bb1ea172df5a2445cb9cd745c3736a7b44a263e721a5caf7e35e83bed527555be62eeca7c9f07e8f827bfbc5ae006b03d52c934c333ca564ca532c6e3d0f0ad85acdc9834bdd95c91b3cc13a6b5f0b101575f3921a8173c778428a98bfe9e5666a65fa39d4dddb7f29d0000000000007a1200000000000001018508dfc4fe50a03eddd23a2a6b167d5ffdcc065a725c4e1c42904dcbc80270d78b16684c83b88bda7443c376dbf4d25be1412935221d66ab0c86cc52756701920c93072d8632a5c25ae43bcbca2732b84b007d884a37c38601f244c957c3401b9f50010000000000000000000000000001018709df142550facc1868d6cdf838b481b7841e240d55eeecbe865e9e646d2a26584fb4dd7951d4f06cf9afd71068a303fdd2d7f1636c83a879d7f41dabdbce6c34df05e3b39d3893c390e938d50760aa0a68a28d5213e2ee7c808232c8bea090c2a8") 13 | ) 14 | 15 | func TestBlockValidate(t *testing.T) { 16 | block := &Block{} 17 | if err := block.Read(bytes.NewReader(serialisedBlock)); err != nil { 18 | t.Errorf("failed to deserialize block: %v", err) 19 | } 20 | 21 | if err := block.Validate(); err != nil { 22 | t.Errorf("TestBlockValidate failed: %v", err) 23 | } 24 | } 25 | 26 | func TestBlockSerialize(t *testing.T) { 27 | block := &Block{} 28 | if err := block.Read(bytes.NewReader(serialisedBlock)); err != nil { 29 | t.Errorf("failed to deserialize block: %v", err) 30 | } 31 | 32 | actual := block.Bytes() 33 | for i := range serialisedBlock { 34 | if serialisedBlock[i] != actual[i] { 35 | t.Errorf("TestBlockSerialize failed: mismatch at byte %d, got\n%x"+ 36 | ", expected\n%x", i, actual, serialisedBlock) 37 | break 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /p2p/handshake.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "github.com/dblokhin/gringo/chain" 12 | "github.com/dblokhin/gringo/consensus" 13 | "github.com/sirupsen/logrus" 14 | "io" 15 | "net" 16 | ) 17 | 18 | // First part of a handshake, sender advertises its version and 19 | // characteristics. 20 | type hand struct { 21 | // protocol version of the sender 22 | Version uint32 23 | // Capabilities of the sender 24 | Capabilities consensus.Capabilities 25 | // randomly generated for each handshake, helps detect self 26 | Nonce uint64 27 | 28 | // genesis block of our chain, only connect to peers on the same chain 29 | Genesis consensus.Hash 30 | 31 | // total difficulty accumulated by the sender, used to check whether sync 32 | // may be needed 33 | TotalDifficulty consensus.Difficulty 34 | // network address of the sender 35 | SenderAddr *net.TCPAddr 36 | ReceiverAddr *net.TCPAddr 37 | 38 | // name of version of the software 39 | UserAgent string 40 | } 41 | 42 | func (h *hand) Bytes() []byte { 43 | buff := new(bytes.Buffer) 44 | 45 | if err := binary.Write(buff, binary.BigEndian, h.Version); err != nil { 46 | logrus.Fatal(err) 47 | } 48 | 49 | if err := binary.Write(buff, binary.BigEndian, uint32(h.Capabilities)); err != nil { 50 | logrus.Fatal(err) 51 | } 52 | 53 | if err := binary.Write(buff, binary.BigEndian, h.Nonce); err != nil { 54 | logrus.Fatal(err) 55 | } 56 | 57 | if err := binary.Write(buff, binary.BigEndian, uint64(h.TotalDifficulty)); err != nil { 58 | logrus.Fatal(err) 59 | } 60 | 61 | if (h.SenderAddr == nil) || (h.ReceiverAddr == nil) { 62 | logrus.Fatal("invalid netaddr (SenderAddr/ReceiverAddr)") 63 | } 64 | 65 | // Write Sender addr 66 | serializeTCPAddr(buff, h.SenderAddr) 67 | 68 | // Write Recv addr 69 | serializeTCPAddr(buff, h.ReceiverAddr) 70 | 71 | // Write user agent [len][string] 72 | binary.Write(buff, binary.BigEndian, uint64(len(h.UserAgent))) 73 | buff.WriteString(h.UserAgent) 74 | 75 | binary.Write(buff, binary.BigEndian, h.Genesis) 76 | 77 | return buff.Bytes() 78 | } 79 | 80 | func (h *hand) Type() uint8 { 81 | return consensus.MsgTypeHand 82 | } 83 | 84 | func (h *hand) Read(r io.Reader) error { 85 | 86 | if err := binary.Read(r, binary.BigEndian, &h.Version); err != nil { 87 | return err 88 | } 89 | 90 | if h.Version != consensus.ProtocolVersion { 91 | return errors.New("incompatibility protocol version") 92 | } 93 | 94 | if err := binary.Read(r, binary.BigEndian, (*uint32)(&h.Capabilities)); err != nil { 95 | return err 96 | } 97 | 98 | if err := binary.Read(r, binary.BigEndian, &h.Nonce); err != nil { 99 | return err 100 | } 101 | 102 | if err := binary.Read(r, binary.BigEndian, (*uint64)(&h.TotalDifficulty)); err != nil { 103 | return err 104 | } 105 | 106 | // read Sender addr 107 | addr, err := deserializeTCPAddr(r) 108 | if err != nil { 109 | return err 110 | } 111 | h.SenderAddr = addr 112 | 113 | // read Recv addr 114 | addr, err = deserializeTCPAddr(r) 115 | if err != nil { 116 | return err 117 | } 118 | h.ReceiverAddr = addr 119 | 120 | // read user agent 121 | var userAgentLen uint64 122 | if err := binary.Read(r, binary.BigEndian, &userAgentLen); err != nil { 123 | return err 124 | } 125 | 126 | buff := make([]byte, userAgentLen) 127 | if _, err := io.ReadFull(r, buff); err != nil { 128 | return err 129 | } 130 | 131 | h.UserAgent = string(buff) 132 | 133 | genesisBuf := make([]byte, 32) 134 | if _, err := io.ReadFull(r, genesisBuf); err != nil { 135 | return err 136 | } 137 | 138 | h.Genesis = genesisBuf 139 | 140 | return nil 141 | } 142 | 143 | // Second part of a handshake, receiver of the first part replies with its own 144 | // version and characteristics. 145 | type shake struct { 146 | // protocol version of the sender 147 | Version uint32 148 | // capabilities of the sender 149 | Capabilities consensus.Capabilities 150 | // total difficulty accumulated by the sender, used to check whether sync 151 | // may be needed 152 | TotalDifficulty consensus.Difficulty 153 | 154 | // name of version of the software 155 | UserAgent string 156 | 157 | // Genesis is the initial block hash on our chain. Used to prevent 158 | // connections to distinct chains. 159 | Genesis consensus.Hash 160 | } 161 | 162 | func (h *shake) Bytes() []byte { 163 | buff := new(bytes.Buffer) 164 | 165 | if err := binary.Write(buff, binary.BigEndian, h.Version); err != nil { 166 | logrus.Fatal(err) 167 | } 168 | 169 | if err := binary.Write(buff, binary.BigEndian, uint32(h.Capabilities)); err != nil { 170 | logrus.Fatal(err) 171 | } 172 | 173 | if err := binary.Write(buff, binary.BigEndian, uint64(h.TotalDifficulty)); err != nil { 174 | logrus.Fatal(err) 175 | } 176 | 177 | // Write user agent [len][string] 178 | binary.Write(buff, binary.BigEndian, uint64(len(h.UserAgent))) 179 | buff.WriteString(h.UserAgent) 180 | 181 | binary.Write(buff, binary.BigEndian, h.Genesis) 182 | 183 | return buff.Bytes() 184 | } 185 | 186 | func (h *shake) Type() uint8 { 187 | return consensus.MsgTypeShake 188 | } 189 | 190 | func (h *shake) Read(r io.Reader) error { 191 | 192 | if err := binary.Read(r, binary.BigEndian, &h.Version); err != nil { 193 | return err 194 | } 195 | 196 | if h.Version != consensus.ProtocolVersion { 197 | return errors.New("incompatibility protocol version") 198 | } 199 | 200 | if err := binary.Read(r, binary.BigEndian, (*uint32)(&h.Capabilities)); err != nil { 201 | return err 202 | } 203 | 204 | if err := binary.Read(r, binary.BigEndian, (*uint64)(&h.TotalDifficulty)); err != nil { 205 | return err 206 | } 207 | 208 | var userAgentLen uint64 209 | if err := binary.Read(r, binary.BigEndian, &userAgentLen); err != nil { 210 | return err 211 | } 212 | 213 | buff := make([]byte, userAgentLen) 214 | if _, err := io.ReadFull(r, buff); err != nil { 215 | return err 216 | } 217 | 218 | h.UserAgent = string(buff) 219 | 220 | genesisBuf := make([]byte, 32) 221 | if _, err := io.ReadFull(r, genesisBuf); err != nil { 222 | return err 223 | } 224 | 225 | h.Genesis = genesisBuf 226 | 227 | return nil 228 | } 229 | 230 | // shakeByHand sends hand to receive shake 231 | func shakeByHand(conn net.Conn) (*shake, error) { 232 | // create hand 233 | // TODO: use the server listen addr 234 | sender, err := net.ResolveTCPAddr("tcp", "0.0.0.0:0") 235 | if err != nil { 236 | logrus.Fatal(err) 237 | } 238 | 239 | receiver := conn.RemoteAddr().(*net.TCPAddr) 240 | 241 | msg := hand{ 242 | Version: consensus.ProtocolVersion, 243 | Capabilities: consensus.CapFullNode, 244 | Nonce: serverNonces.NextNonce(), 245 | TotalDifficulty: consensus.Difficulty(1), 246 | SenderAddr: sender, 247 | ReceiverAddr: receiver, 248 | UserAgent: userAgent, 249 | Genesis: chain.Testnet4.Hash(), 250 | } 251 | 252 | // Send own hand 253 | if _, err := WriteMessage(conn, &msg); err != nil { 254 | return nil, err 255 | } 256 | 257 | // Read peer shake 258 | sh := new(shake) 259 | if _, err := ReadMessage(conn, sh); err != nil { 260 | return nil, err 261 | } 262 | 263 | return sh, nil 264 | } 265 | 266 | // handByShake sends shake and return received hand 267 | func handByShake(conn net.Conn) (*hand, error) { 268 | 269 | var h hand 270 | 271 | // Recv remote hand 272 | if _, err := ReadMessage(conn, &h); err != nil { 273 | return nil, err 274 | } 275 | 276 | // Check nonce to detect connection to ourselves 277 | if serverNonces.Consist(h.Nonce) { 278 | return &h, errors.New("detect connection to ourselves by nonce") 279 | } 280 | 281 | // Send shake 282 | msg := shake{ 283 | Version: consensus.ProtocolVersion, 284 | Capabilities: consensus.CapFullNode, 285 | TotalDifficulty: consensus.Difficulty(1), 286 | UserAgent: userAgent, 287 | } 288 | if _, err := WriteMessage(conn, &msg); err != nil { 289 | return nil, err 290 | } 291 | 292 | return &h, nil 293 | } 294 | -------------------------------------------------------------------------------- /p2p/pool.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "github.com/dblokhin/gringo/consensus" 11 | "github.com/sirupsen/logrus" 12 | "net" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | // maxOnlineConnections should be override 18 | // TODO: setting up by config 19 | var ( 20 | maxOnlineConnections = 15 21 | maxPeersTableSize = 10000 22 | ) 23 | 24 | // newPeersPool returns peers pool instance 25 | func newPeersPool(sync *Syncer) *peersPool { 26 | pp := &peersPool{ 27 | connected: 0, 28 | sync: sync, 29 | pool: make(chan struct{}, maxOnlineConnections), 30 | quit: make(chan int), 31 | PeersTable: make(map[string]*peerInfo), 32 | ConnectedPeers: make(map[string]*peerInfo), 33 | } 34 | 35 | return pp 36 | } 37 | 38 | // peersPool control connections with peers 39 | type peersPool struct { 40 | ptmu sync.Mutex // mutex for PeersTable 41 | cpmu sync.Mutex // mutex for ConnectedPeers 42 | bnmu sync.Mutex // mutex for BannedPeers 43 | 44 | connected int32 45 | sync *Syncer 46 | 47 | pool chan struct{} 48 | quit chan int 49 | 50 | // all peers 51 | PeersTable map[string]*peerInfo 52 | 53 | // connected peers table 54 | ConnectedPeers map[string]*peerInfo 55 | 56 | // banned peers 57 | BannedPeers map[string]struct{} 58 | } 59 | 60 | // Ban closes connection & ban peer 61 | func (pp *peersPool) Ban(addr string) { 62 | pp.ptmu.Lock() 63 | peerInfo, ok := pp.PeersTable[addr] 64 | pp.ptmu.Unlock() 65 | 66 | if !ok { 67 | return 68 | } 69 | 70 | // Mark banned & Close connection 71 | peerInfo.Status = psBanned 72 | peerInfo.Peer.Close() 73 | 74 | // Add to ban list 75 | pp.bnmu.Lock() 76 | pp.BannedPeers[addr] = struct{}{} 77 | pp.bnmu.Unlock() 78 | 79 | // Clear the peers table 80 | pp.ptmu.Lock() 81 | delete(pp.PeersTable, addr) 82 | pp.ptmu.Unlock() 83 | } 84 | 85 | // IsBan returns true if addr is banned 86 | func (pp *peersPool) IsBan(addr string) bool { 87 | pp.bnmu.Lock() 88 | defer pp.bnmu.Unlock() 89 | 90 | _, ok := pp.BannedPeers[addr] 91 | return ok 92 | } 93 | 94 | // AddPeer adds new peer addr to pm 95 | func (pp *peersPool) Add(addr string) { 96 | netAddr, err := net.ResolveTCPAddr("tcp", addr) 97 | if err != nil { 98 | // dont add invalid tcp addrs 99 | return 100 | } 101 | 102 | // FIXME: discard another IPs 103 | if netAddr.IP.IsMulticast() { 104 | return 105 | } 106 | 107 | if netAddr.Port == 0 { 108 | return 109 | } 110 | 111 | pp.ptmu.Lock() 112 | defer pp.ptmu.Unlock() 113 | 114 | // Don't add if big peer table 115 | if len(pp.PeersTable) > maxPeersTableSize { 116 | return 117 | } 118 | 119 | // Checks for existing 120 | if _, ok := pp.PeersTable[addr]; ok { 121 | return 122 | } 123 | 124 | // Adds new 125 | pp.PeersTable[addr] = &peerInfo{ 126 | Status: psNew, 127 | Peer: nil, 128 | ProtocolVersion: 0, 129 | Height: 0, 130 | TotalDifficulty: consensus.ZeroDifficulty, 131 | Capabilities: consensus.CapUnknown, 132 | LastConn: time.Unix(0, 0), 133 | } 134 | } 135 | 136 | // PeerAddrs returns peer list (no banned) 137 | func (pp *peersPool) Peers(capabilities consensus.Capabilities) *PeerAddrs { 138 | addrs := make([]*net.TCPAddr, 0) 139 | 140 | // Getting peers randomly 141 | pp.ptmu.Lock() 142 | defer pp.ptmu.Unlock() 143 | 144 | for addr, peerInfo := range pp.PeersTable { 145 | if peerInfo.Status == psBanned || peerInfo.Status == psFailedConn { 146 | continue 147 | } 148 | 149 | // filter by capabilities 150 | if (peerInfo.Capabilities & capabilities) != capabilities { 151 | continue 152 | } 153 | 154 | if netAddr, err := net.ResolveTCPAddr("tcp", addr); err == nil { 155 | addrs = append(addrs, netAddr) 156 | } else { 157 | logrus.Error(err) 158 | } 159 | 160 | if len(addrs) == consensus.MaxPeerAddrs { 161 | break 162 | } 163 | } 164 | 165 | return &PeerAddrs{ 166 | peers: addrs, 167 | } 168 | } 169 | 170 | // PeerInfo returns peer structure 171 | func (pp *peersPool) PeerInfo(addr string) *peerInfo { 172 | pp.ptmu.Lock() 173 | peerInfo, ok := pp.PeersTable[addr] 174 | pp.ptmu.Unlock() 175 | if ok { 176 | return peerInfo 177 | } 178 | 179 | return nil 180 | } 181 | 182 | // PropagateBlock propagates block to connected peers 183 | func (pp *peersPool) PropagateBlock(block *consensus.Block) { 184 | pp.cpmu.Lock() 185 | defer pp.cpmu.Unlock() 186 | 187 | for _, pi := range pp.ConnectedPeers { 188 | go func(peerInfo *peerInfo) { 189 | // propagate if peer height or totalDiff less than newest block 190 | if peerInfo.Height < block.Header.Height || peerInfo.TotalDifficulty < block.Header.TotalDifficulty { 191 | if peer := peerInfo.Peer; peer != nil { 192 | peer.SendBlock(block) 193 | } 194 | } 195 | }(pi) 196 | } 197 | } 198 | 199 | // connectPeer connects peer from peerTable 200 | func (pp *peersPool) connectPeer(addr string) error { 201 | // for empty string nonerror exit 202 | if len(addr) == 0 { 203 | return nil 204 | } 205 | 206 | if pp.connected > int32(maxOnlineConnections) { 207 | return errors.New("too big online peers connections") 208 | } 209 | 210 | pp.ptmu.Lock() 211 | peerInfo, ok := pp.PeersTable[addr] 212 | pp.ptmu.Unlock() 213 | 214 | if !ok { 215 | return errors.New("peer doesn't exists at peersTable") 216 | } 217 | 218 | peerInfo.Lock() 219 | defer peerInfo.Unlock() 220 | 221 | if peerInfo.Status == psBanned || peerInfo.Status == psConnected { 222 | logrus.Debug("dont connect to banned host (or already connected)") 223 | return nil 224 | } 225 | 226 | peerConn, err := NewPeer(pp.sync, addr) 227 | if err != nil { 228 | peerInfo.Status = psFailedConn 229 | return err 230 | } 231 | 232 | // Check the Protocol version 233 | if peerConn.Info.Version != consensus.ProtocolVersion { 234 | return fmt.Errorf("unexpected protocolVersion: %d", peerConn.Info.Version) 235 | } 236 | 237 | pp.connected++ 238 | 239 | // update peers table 240 | peerInfo.Peer = peerConn 241 | peerInfo.Status = psConnected 242 | peerInfo.LastConn = time.Now() 243 | 244 | peerInfo.ProtocolVersion = peerConn.Info.Version 245 | peerInfo.Height = peerConn.Info.Height 246 | peerInfo.TotalDifficulty = peerConn.Info.TotalDifficulty 247 | peerInfo.Capabilities = peerConn.Info.Capabilities 248 | 249 | // update connected peers 250 | pp.cpmu.Lock() 251 | pp.ConnectedPeers[addr] = peerInfo 252 | pp.cpmu.Unlock() 253 | 254 | // And send ping / peers request 255 | peerConn.Start() 256 | peerConn.SendPing() 257 | peerConn.SendPeerRequest(consensus.CapFullNode) 258 | 259 | // on disconnect update info 260 | go func() { 261 | peerConn.WaitForDisconnect() 262 | logrus.Infof("closed peer connection (%s)", addr) 263 | 264 | // update peers & connected peers tables 265 | peerInfo.Lock() 266 | peerInfo.Status = psDisconnected 267 | peerInfo.Unlock() 268 | 269 | // clean connected peers 270 | pp.connected-- 271 | pp.cpmu.Lock() 272 | delete(pp.ConnectedPeers, addr) 273 | pp.cpmu.Unlock() 274 | 275 | <-pp.pool 276 | }() 277 | 278 | return nil 279 | } 280 | 281 | // Run starts network activity 282 | func (pp *peersPool) Run() { 283 | 284 | out: 285 | for { 286 | select { 287 | case <-pp.quit: 288 | break out 289 | 290 | case pp.pool <- struct{}{}: 291 | if err := pp.connectPeer(pp.notConnected()); err != nil { 292 | logrus.Error(err) 293 | <-pp.pool 294 | } 295 | 296 | time.Sleep(time.Second) 297 | } 298 | } 299 | 300 | // Close all connections 301 | pp.ptmu.Lock() 302 | defer pp.ptmu.Unlock() 303 | 304 | for _, pi := range pp.PeersTable { 305 | go func(peerInfo *peerInfo) { 306 | peerInfo.Lock() 307 | peerInfo.Peer.Close() 308 | peerInfo.Status = psDisconnected 309 | peerInfo.Unlock() 310 | }(pi) 311 | 312 | } 313 | } 314 | 315 | // Stop stops network activity 316 | func (pp *peersPool) Stop() { 317 | close(pp.quit) 318 | } 319 | 320 | // notConnected returns peer addr from table which not active 321 | func (pp *peersPool) notConnected() string { 322 | pp.ptmu.Lock() 323 | defer pp.ptmu.Unlock() 324 | 325 | // first, find good peers 326 | for addr, peerInfo := range pp.PeersTable { 327 | if peerInfo.Status == psNew || peerInfo.Status == psDisconnected { 328 | return addr 329 | } 330 | } 331 | 332 | // second, try to open conn with failed nodes 333 | for addr, peer := range pp.PeersTable { 334 | if peer.Status == psFailedConn { 335 | return addr 336 | } 337 | } 338 | 339 | return "" 340 | } 341 | 342 | type peerInfo struct { 343 | sync.Mutex 344 | 345 | Status peerStatus 346 | Peer *Peer 347 | 348 | ProtocolVersion uint32 349 | Height uint64 350 | TotalDifficulty consensus.Difficulty 351 | Capabilities consensus.Capabilities 352 | 353 | LastConn time.Time 354 | } 355 | 356 | type peerStatus int 357 | 358 | const ( 359 | psNew peerStatus = iota 360 | psConnected 361 | psBanned 362 | psDisconnected 363 | psFailedConn 364 | ) 365 | -------------------------------------------------------------------------------- /p2p/messages.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "fmt" 12 | "github.com/dblokhin/gringo/consensus" 13 | "github.com/sirupsen/logrus" 14 | "io" 15 | "net" 16 | ) 17 | 18 | // Header is header of any protocol message, used to identify incoming messages 19 | type Header struct { 20 | // magic number 21 | magic [2]byte 22 | // Type typo of the message. 23 | Type uint8 24 | // Len length of the message in bytes. 25 | Len uint64 26 | } 27 | 28 | // Bytes serialises the header to its on-the-wire representation. 29 | func (h *Header) Bytes() []byte { 30 | buff := new(bytes.Buffer) 31 | 32 | if _, err := buff.Write(h.magic[:]); err != nil { 33 | logrus.Fatal(err) 34 | } 35 | 36 | if err := binary.Write(buff, binary.BigEndian, h.Type); err != nil { 37 | logrus.Fatal(err) 38 | } 39 | 40 | if err := binary.Write(buff, binary.BigEndian, h.Len); err != nil { 41 | logrus.Fatal(err) 42 | } 43 | 44 | return buff.Bytes() 45 | } 46 | 47 | // Write writes header as binary data to writer 48 | func (h *Header) Write(wr io.Writer) error { 49 | if _, err := wr.Write(h.magic[:]); err != nil { 50 | return err 51 | } 52 | if err := binary.Write(wr, binary.BigEndian, h.Type); err != nil { 53 | return err 54 | } 55 | 56 | return binary.Write(wr, binary.BigEndian, h.Len) 57 | } 58 | 59 | // Read reads from reader & fill struct 60 | func (h *Header) Read(r io.Reader) error { 61 | if _, err := io.ReadFull(r, h.magic[:]); err != nil { 62 | return err 63 | } 64 | 65 | if !h.validateMagic() { 66 | logrus.Debug("got magic: ", h.magic[:]) 67 | return errors.New("invalid magic code") 68 | } 69 | 70 | if err := binary.Read(r, binary.BigEndian, &h.Type); err != nil { 71 | return err 72 | } 73 | 74 | return binary.Read(r, binary.BigEndian, &h.Len) 75 | } 76 | 77 | // validateMagic verifies magic code 78 | func (h Header) validateMagic() bool { 79 | return bytes.Equal(h.magic[:], consensus.MagicCode[:]) 80 | } 81 | 82 | // Ping request 83 | type Ping struct { 84 | // total difficulty accumulated by the sender, used to check whether sync 85 | // may be needed 86 | TotalDifficulty consensus.Difficulty 87 | // total height 88 | Height uint64 89 | } 90 | 91 | // Bytes implements Message interface 92 | func (p *Ping) Bytes() []byte { 93 | buff := new(bytes.Buffer) 94 | 95 | if err := binary.Write(buff, binary.BigEndian, uint64(p.TotalDifficulty)); err != nil { 96 | logrus.Fatal(err) 97 | } 98 | 99 | if err := binary.Write(buff, binary.BigEndian, uint64(p.Height)); err != nil { 100 | logrus.Fatal(err) 101 | } 102 | 103 | return buff.Bytes() 104 | } 105 | 106 | // Type implements Message interface 107 | func (p *Ping) Type() uint8 { 108 | return consensus.MsgTypePing 109 | } 110 | 111 | // Read implements Message interface 112 | func (p *Ping) Read(r io.Reader) error { 113 | 114 | if err := binary.Read(r, binary.BigEndian, (*uint64)(&p.TotalDifficulty)); err != nil { 115 | return err 116 | } 117 | 118 | return binary.Read(r, binary.BigEndian, (*uint64)(&p.Height)) 119 | } 120 | 121 | // String implements String() interface 122 | func (p Ping) String() string { 123 | return fmt.Sprintf("%#v", p) 124 | } 125 | 126 | // Pong response same as Ping 127 | type Pong struct { 128 | Ping 129 | } 130 | 131 | // Type implements Messagee interface 132 | func (p *Pong) Type() uint8 { 133 | return consensus.MsgTypePong 134 | } 135 | 136 | // GetPeerAddrs asks for other peers addresses, required for network discovery. 137 | type GetPeerAddrs struct { 138 | // filters on the capabilities we'd like the peers to have 139 | Capabilities consensus.Capabilities 140 | } 141 | 142 | // Bytes implements Message interface 143 | func (p *GetPeerAddrs) Bytes() []byte { 144 | buff := new(bytes.Buffer) 145 | 146 | if err := binary.Write(buff, binary.BigEndian, uint32(p.Capabilities)); err != nil { 147 | logrus.Fatal(err) 148 | } 149 | 150 | return buff.Bytes() 151 | } 152 | 153 | // Type implements Message interface 154 | func (p *GetPeerAddrs) Type() uint8 { 155 | return consensus.MsgTypeGetPeerAddrs 156 | } 157 | 158 | // Read implements Message interface 159 | func (p *GetPeerAddrs) Read(r io.Reader) error { 160 | 161 | return binary.Read(r, binary.BigEndian, (*uint32)(&p.Capabilities)) 162 | } 163 | 164 | // String implements String() interface 165 | func (p GetPeerAddrs) String() string { 166 | return fmt.Sprintf("%#v", p) 167 | } 168 | 169 | // PeerError sending an error back (usually followed by closing conn) 170 | type PeerError struct { 171 | // error code 172 | Code uint32 173 | // slightly more user friendly message 174 | Message string 175 | } 176 | 177 | // Bytes implements Message interface 178 | func (p *PeerError) Bytes() []byte { 179 | buff := new(bytes.Buffer) 180 | 181 | if err := binary.Write(buff, binary.BigEndian, uint32(p.Code)); err != nil { 182 | logrus.Fatal(err) 183 | } 184 | 185 | // Write user agent [len][string] 186 | if err := binary.Write(buff, binary.BigEndian, uint64(len(p.Message))); err != nil { 187 | logrus.Fatal(err) 188 | } 189 | buff.WriteString(p.Message) 190 | return buff.Bytes() 191 | } 192 | 193 | // Type implements Message interface 194 | func (p *PeerError) Type() uint8 { 195 | return consensus.MsgTypeError 196 | } 197 | 198 | // Read implements Message interface 199 | func (p *PeerError) Read(r io.Reader) error { 200 | 201 | if err := binary.Read(r, binary.BigEndian, (*uint32)(&p.Code)); err != nil { 202 | return err 203 | } 204 | 205 | var messageLen uint64 206 | if err := binary.Read(r, binary.BigEndian, &messageLen); err != nil { 207 | return err 208 | } 209 | 210 | buff := make([]byte, messageLen) 211 | if _, err := io.ReadFull(r, buff); err != nil { 212 | return err 213 | } 214 | 215 | p.Message = string(buff) 216 | return nil 217 | } 218 | 219 | // String implements String() interface 220 | func (p PeerError) String() string { 221 | return fmt.Sprintf("%#v", p) 222 | } 223 | 224 | // PeerAddrs we know of that are fresh enough, in response to GetPeerAddrs 225 | type PeerAddrs struct { 226 | peers []*net.TCPAddr 227 | } 228 | 229 | // Bytes implements Message interface 230 | func (p *PeerAddrs) Bytes() []byte { 231 | buff := new(bytes.Buffer) 232 | 233 | if len(p.peers) > consensus.MaxPeerAddrs { 234 | logrus.Debug("length peers: ", len(p.peers)) 235 | logrus.Fatal(errors.New("too big peer addrs count for sending")) 236 | } 237 | 238 | if err := binary.Write(buff, binary.BigEndian, uint32(len(p.peers))); err != nil { 239 | logrus.Fatal(err) 240 | } 241 | 242 | for _, peerAddr := range p.peers { 243 | serializeTCPAddr(buff, peerAddr) 244 | } 245 | 246 | return buff.Bytes() 247 | } 248 | 249 | // Type implements Message interface 250 | func (p *PeerAddrs) Type() uint8 { 251 | return consensus.MsgTypePeerAddrs 252 | } 253 | 254 | // Read implements Message interface 255 | func (p *PeerAddrs) Read(r io.Reader) error { 256 | var peersCount uint32 257 | 258 | if err := binary.Read(r, binary.BigEndian, &peersCount); err != nil { 259 | return err 260 | } 261 | 262 | if peersCount > consensus.MaxPeerAddrs { 263 | return errors.New("too big peer addrs count") 264 | } 265 | 266 | for i := uint32(0); i < peersCount; i++ { 267 | addr, err := deserializeTCPAddr(r) 268 | if err != nil { 269 | return err 270 | } 271 | 272 | p.peers = append(p.peers, addr) 273 | } 274 | 275 | return nil 276 | } 277 | 278 | // String implements String() interface 279 | func (p PeerAddrs) String() string { 280 | return fmt.Sprintf("%#v", p) 281 | } 282 | 283 | // GetBlock message for requesting block by hash 284 | type GetBlock struct { 285 | Hash consensus.Hash 286 | } 287 | 288 | // Bytes implements Message interface 289 | func (h *GetBlock) Bytes() []byte { 290 | if len(h.Hash) != consensus.BlockHashSize { 291 | logrus.Fatal(errors.New("invalid block hash len")) 292 | } 293 | 294 | return h.Hash 295 | } 296 | 297 | // Type implements Message interface 298 | func (h *GetBlock) Type() uint8 { 299 | return consensus.MsgTypeGetBlock 300 | } 301 | 302 | // Read implements Message interface 303 | func (h *GetBlock) Read(r io.Reader) error { 304 | 305 | hash := make([]byte, consensus.BlockHashSize) 306 | _, err := io.ReadFull(r, hash) 307 | 308 | h.Hash = hash 309 | return err 310 | } 311 | 312 | // String implements String() interface 313 | func (h GetBlock) String() string { 314 | return fmt.Sprintf("%#v", h) 315 | } 316 | 317 | // BlockHeader is a p2p message that serves as a notification that there is a 318 | // new block. If this block isn't known then the block can be requested from 319 | // the network. BlockHeaders are unsolicited rather than as a response to a 320 | // request. 321 | type BlockHeader struct { 322 | // Header is a single block header. 323 | Header consensus.BlockHeader 324 | } 325 | 326 | // Bytes implements Message interface 327 | func (h *BlockHeader) Bytes() []byte { 328 | buff := new(bytes.Buffer) 329 | 330 | if _, err := buff.Write(h.Header.Bytes()); err != nil { 331 | logrus.Fatal(err) 332 | } 333 | 334 | return buff.Bytes() 335 | } 336 | 337 | // Type implements Message interface 338 | func (h *BlockHeader) Type() uint8 { 339 | return consensus.MsgTypeHeader 340 | } 341 | 342 | // Read implements Message interface 343 | func (h *BlockHeader) Read(r io.Reader) error { 344 | return h.Header.Read(r) 345 | } 346 | 347 | // String implements String() interface 348 | func (h BlockHeader) String() string { 349 | return fmt.Sprintf("%#v", h) 350 | } 351 | 352 | // BlockHeaders message with grin headers 353 | type BlockHeaders struct { 354 | Headers []consensus.BlockHeader 355 | } 356 | 357 | // Bytes implements Message interface 358 | func (h *BlockHeaders) Bytes() []byte { 359 | buff := new(bytes.Buffer) 360 | 361 | // check the bounds of h.Headers & set the limits 362 | if len(h.Headers) > consensus.MaxBlockHeaders { 363 | logrus.Fatal(errors.New("invalid headers len in BlockHeaders")) 364 | } 365 | 366 | if err := binary.Write(buff, binary.BigEndian, uint16(len(h.Headers))); err != nil { 367 | logrus.Fatal(err) 368 | } 369 | 370 | for _, header := range h.Headers { 371 | if _, err := buff.Write(header.Bytes()); err != nil { 372 | logrus.Fatal(err) 373 | } 374 | } 375 | 376 | return buff.Bytes() 377 | } 378 | 379 | // Type implements Message interface 380 | func (h *BlockHeaders) Type() uint8 { 381 | return consensus.MsgTypeHeaders 382 | } 383 | 384 | // Read implements Message interface 385 | func (h *BlockHeaders) Read(r io.Reader) error { 386 | 387 | var count uint16 388 | if err := binary.Read(r, binary.BigEndian, &count); err != nil { 389 | return err 390 | } 391 | 392 | if int(count) > consensus.MaxBlockHeaders { 393 | return errors.New("too big block headers len from peer") 394 | } 395 | 396 | h.Headers = make([]consensus.BlockHeader, count) 397 | for i := 0; i < int(count); i++ { 398 | if err := h.Headers[i].Read(r); err != nil { 399 | return err 400 | } 401 | } 402 | 403 | return nil 404 | } 405 | 406 | // String implements String() interface 407 | func (h BlockHeaders) String() string { 408 | return fmt.Sprintf("%#v", h) 409 | } 410 | 411 | // GetBlockHeaders message for requesting headers 412 | type GetBlockHeaders struct { 413 | Locator consensus.Locator 414 | } 415 | 416 | // Bytes implements Message interface 417 | func (h *GetBlockHeaders) Bytes() []byte { 418 | return h.Locator.Bytes() 419 | } 420 | 421 | // Type implements Message interface 422 | func (h *GetBlockHeaders) Type() uint8 { 423 | return consensus.MsgTypeGetHeaders 424 | } 425 | 426 | // Read implements Message interface 427 | func (h *GetBlockHeaders) Read(r io.Reader) error { 428 | return h.Locator.Read(r) 429 | } 430 | 431 | // String implements String() interface 432 | func (h GetBlockHeaders) String() string { 433 | return fmt.Sprintf("%#v", h) 434 | } 435 | -------------------------------------------------------------------------------- /p2p/peer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package p2p 6 | 7 | import ( 8 | "bufio" 9 | "bytes" 10 | "encoding/hex" 11 | "errors" 12 | "fmt" 13 | "github.com/dblokhin/gringo/consensus" 14 | "github.com/sirupsen/logrus" 15 | "io" 16 | "net" 17 | "sync" 18 | "sync/atomic" 19 | ) 20 | 21 | // Peer is a participant of p2p network 22 | type Peer struct { 23 | conn net.Conn 24 | sync *Syncer 25 | 26 | // The following fields are only meant to be used *atomically* 27 | bytesReceived uint64 28 | bytesSent uint64 29 | 30 | quit chan struct{} 31 | wg sync.WaitGroup 32 | 33 | // Queue for sending message 34 | sendQueue chan Message 35 | 36 | // disconnect flag 37 | disconnect int32 38 | 39 | // Network addr 40 | Addr string 41 | 42 | // Info connected peer 43 | Info struct { 44 | // protocol version of the sender 45 | Version uint32 46 | // capabilities of the sender 47 | Capabilities consensus.Capabilities 48 | // total difficulty accumulated by the sender, used to check whether sync 49 | // may be needed 50 | TotalDifficulty consensus.Difficulty 51 | // name of version of the software 52 | UserAgent string 53 | // Height 54 | Height uint64 55 | } 56 | } 57 | 58 | // NewPeer connects to peer 59 | func NewPeer(sync *Syncer, addr string) (*Peer, error) { 60 | 61 | logrus.Infof("starting new peer (%s)", addr) 62 | tcpAddr, err := net.ResolveTCPAddr("tcp", addr) 63 | if err != nil { 64 | return nil, err 65 | } 66 | 67 | // dial connection 68 | conn, err := net.DialTCP("tcp", nil, tcpAddr) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | logrus.Infof("connected to peer (%s)", addr) 74 | shake, err := shakeByHand(conn) 75 | if err != nil { 76 | return nil, err 77 | } 78 | 79 | p := new(Peer) 80 | p.conn = conn 81 | p.sync = sync 82 | p.quit = make(chan struct{}) 83 | p.sendQueue = make(chan Message) 84 | 85 | // Store the network addr 86 | p.Addr = addr 87 | 88 | p.Info.Version = shake.Version 89 | p.Info.Capabilities = shake.Capabilities 90 | p.Info.TotalDifficulty = shake.TotalDifficulty 91 | p.Info.UserAgent = shake.UserAgent 92 | 93 | return p, nil 94 | } 95 | 96 | // AcceptNewPeer creates peer accepting listening server conn 97 | func AcceptNewPeer(conn net.Conn) (*Peer, error) { 98 | 99 | logrus.Info("accept new peer") 100 | hand, err := handByShake(conn) 101 | if err != nil { 102 | return nil, err 103 | } 104 | 105 | p := new(Peer) 106 | p.conn = conn 107 | p.quit = make(chan struct{}) 108 | p.sendQueue = make(chan Message) 109 | 110 | p.Info.Version = hand.Version 111 | p.Info.Capabilities = hand.Capabilities 112 | p.Info.TotalDifficulty = hand.TotalDifficulty 113 | p.Info.UserAgent = hand.UserAgent 114 | 115 | return p, nil 116 | } 117 | 118 | // Start starts loop listening, write handler and so on 119 | func (p *Peer) Start() { 120 | p.wg.Add(2) 121 | go p.writeHandler() 122 | go p.readHandler() 123 | } 124 | 125 | // writeHandler is a goroutine dedicated to reading messages off of an incoming 126 | // queue, and writing them out to the wire. 127 | // 128 | // NOTE: This method MUST be run as a goroutine. 129 | func (p *Peer) writeHandler() { 130 | var exitError error 131 | 132 | out: 133 | for { 134 | select { 135 | case msg := <-p.sendQueue: 136 | // Ensure that conn is alive 137 | if atomic.LoadInt32(&p.disconnect) != 0 { 138 | break out 139 | } 140 | 141 | var written uint64 142 | if written, exitError = WriteMessage(p.conn, msg); exitError != nil { 143 | break out 144 | } 145 | 146 | atomic.AddUint64(&p.bytesSent, written) 147 | 148 | case <-p.quit: 149 | exitError = errors.New("peer exiting") 150 | break out 151 | } 152 | } 153 | 154 | p.wg.Done() 155 | p.Disconnect(exitError) 156 | } 157 | 158 | // WriteMessage places msg to send queue 159 | func (p *Peer) WriteMessage(msg Message) { 160 | select { 161 | case <-p.quit: 162 | logrus.Info("cannot send message, peer is shutting down") 163 | case p.sendQueue <- msg: 164 | } 165 | } 166 | 167 | // readHandler is responsible for reading messages off the wire in series, then 168 | // properly dispatching the handling of the message to the proper subsystem. 169 | // 170 | // NOTE: This method MUST be run as a goroutine. 171 | func (p *Peer) readHandler() { 172 | var exitError error 173 | input := bufio.NewReader(p.conn) 174 | header := new(Header) 175 | 176 | out: 177 | for atomic.LoadInt32(&p.disconnect) == 0 { 178 | if exitError = header.Read(input); exitError != nil { 179 | logrus.Debugf("Failed to read message from peer %v", p.conn.RemoteAddr()) 180 | break out 181 | } 182 | 183 | if header.Len > consensus.MaxMsgLen { 184 | exitError = errors.New("too big message size") 185 | break out 186 | } 187 | 188 | // Read the whole message. If the peer disconnects mid-way through 189 | // ReadFull will return an error. 190 | readBuffer := make([]byte, header.Len) 191 | _, err := io.ReadFull(input, readBuffer) 192 | if err != nil { 193 | logrus.Infof("Failed to read message: %v", err) 194 | break out 195 | } 196 | 197 | // Print the message for debugging purposes. 198 | logrus.Debugf("Received message from %s: %02x%02x", p.conn.RemoteAddr(), header.Bytes(), readBuffer) 199 | 200 | rl := bytes.NewReader(readBuffer) 201 | 202 | switch header.Type { 203 | case consensus.MsgTypePing: 204 | // update peer info & send Pong 205 | var msg Ping 206 | if exitError = msg.Read(rl); exitError != nil { 207 | break out 208 | } 209 | 210 | logrus.Debugf("Received Ping from %s", p.conn.RemoteAddr().String()) 211 | p.sync.ProcessMessage(p, &msg) 212 | 213 | case consensus.MsgTypePong: 214 | // update peer info 215 | var msg Pong 216 | if exitError = msg.Read(rl); exitError != nil { 217 | break out 218 | } 219 | 220 | p.sync.ProcessMessage(p, &msg) 221 | 222 | case consensus.MsgTypeGetPeerAddrs: 223 | logrus.Infof("receiving peer request (%s)", p.conn.RemoteAddr().String()) 224 | 225 | var msg GetPeerAddrs 226 | if exitError = msg.Read(rl); exitError != nil { 227 | break out 228 | } 229 | 230 | p.sync.ProcessMessage(p, &msg) 231 | 232 | case consensus.MsgTypePeerAddrs: 233 | logrus.Infof("receiving peer addrs (%s)", p.conn.RemoteAddr().String()) 234 | 235 | var msg PeerAddrs 236 | if exitError = msg.Read(rl); exitError != nil { 237 | break out 238 | } 239 | 240 | logrus.Infof("received %d peers", len(msg.peers)) 241 | p.sync.ProcessMessage(p, &msg) 242 | 243 | case consensus.MsgTypeGetHeaders: 244 | logrus.Infof("receiving header request (%s)", p.conn.RemoteAddr().String()) 245 | 246 | var msg GetBlockHeaders 247 | if exitError = msg.Read(rl); exitError != nil { 248 | break out 249 | } 250 | 251 | p.sync.ProcessMessage(p, &msg) 252 | 253 | case consensus.MsgTypeHeader: 254 | logrus.Infof("header notification from peer %s", p.conn.RemoteAddr().String()) 255 | 256 | var msg BlockHeader 257 | if exitError = msg.Read(rl); exitError != nil { 258 | break out 259 | } 260 | 261 | p.sync.ProcessMessage(p, &msg) 262 | 263 | case consensus.MsgTypeHeaders: 264 | logrus.Infof("receiving headers (%s)", p.conn.RemoteAddr().String()) 265 | 266 | var msg BlockHeaders 267 | if exitError = msg.Read(rl); exitError != nil { 268 | break out 269 | } 270 | 271 | logrus.Debug("headers: ", msg.Headers) 272 | p.sync.ProcessMessage(p, &msg) 273 | 274 | case consensus.MsgTypeGetBlock: 275 | logrus.Infof("receiving block request (%s)", p.conn.RemoteAddr().String()) 276 | 277 | var msg GetBlock 278 | if exitError = msg.Read(rl); exitError != nil { 279 | break out 280 | } 281 | 282 | p.sync.ProcessMessage(p, &msg) 283 | 284 | case consensus.MsgTypeBlock: 285 | logrus.Infof("receiving block (%s)", p.conn.RemoteAddr().String()) 286 | 287 | var msg consensus.Block 288 | if exitError = msg.Read(rl); exitError != nil { 289 | break out 290 | } 291 | 292 | logrus.Info("block hash: ", hex.EncodeToString(msg.Header.Hash())) 293 | p.sync.ProcessMessage(p, &msg) 294 | 295 | case consensus.MsgTypeGetCompactBlock: 296 | logrus.Infof("receiving compact block request (%s)", p.conn.RemoteAddr().String()) 297 | // TODO: impl it 298 | 299 | case consensus.MsgTypeCompactBlock: 300 | logrus.Infof("receiving compact block (%s)", p.conn.RemoteAddr().String()) 301 | 302 | var msg consensus.CompactBlock 303 | if exitError = msg.Read(rl); exitError != nil { 304 | break out 305 | } 306 | 307 | // TODO: process compact block 308 | logrus.Info("compact block hash: ", hex.EncodeToString(msg.Header.Hash())) 309 | 310 | case consensus.MsgTypeTransaction: 311 | logrus.Infof("receiving transaction (%s)", p.conn.RemoteAddr().String()) 312 | 313 | var msg consensus.Transaction 314 | if exitError = msg.Read(rl); exitError != nil { 315 | break out 316 | } 317 | 318 | logrus.Debug("transaction: ", msg) 319 | p.sync.ProcessMessage(p, &msg) 320 | 321 | default: 322 | // Print the content of the unknown message. 323 | buff := make([]byte, header.Len) 324 | if _, err := io.ReadFull(rl, buff); err != nil { 325 | logrus.Debugf("failed to read message body: %v", err) 326 | break out 327 | } 328 | 329 | logrus.Debugf("received unexpected message: %02x%02x", header.Bytes(), buff) 330 | 331 | exitError = fmt.Errorf("received unexpected message from peer: %v", header) 332 | break out 333 | } 334 | 335 | // update recv bytes counter 336 | atomic.AddUint64(&p.bytesReceived, header.Len+consensus.HeaderLen) 337 | } 338 | 339 | p.wg.Done() 340 | p.Disconnect(exitError) 341 | } 342 | 343 | // Disconnect closes peer connection 344 | func (p *Peer) Disconnect(reason error) { 345 | if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) { 346 | return 347 | } 348 | 349 | logrus.Info("Disconnect peer: ", reason) 350 | 351 | close(p.quit) 352 | p.conn.Close() 353 | p.wg.Wait() 354 | } 355 | 356 | // Close the connection to the remote peer 357 | func (p *Peer) Close() { 358 | p.Disconnect(errors.New("closing peer")) 359 | } 360 | 361 | // WaitForDisconnect waits until the peer has disconnected. 362 | func (p *Peer) WaitForDisconnect() { 363 | <-p.quit 364 | p.wg.Wait() 365 | } 366 | 367 | // SendPing sends Ping request to peer 368 | func (p *Peer) SendPing() { 369 | logrus.Infof("Sending Ping to %s", p.conn.RemoteAddr()) 370 | 371 | var request Ping 372 | request.TotalDifficulty = consensus.Difficulty(1) 373 | request.Height = 1 374 | 375 | p.WriteMessage(&request) 376 | } 377 | 378 | // SendBlockRequest sends request block by hash 379 | func (p *Peer) SendBlockRequest(hash consensus.Hash) { 380 | logrus.Infof("sending block request (%s)", hex.EncodeToString(hash[:6])) 381 | 382 | var request GetBlock 383 | request.Hash = hash 384 | 385 | p.WriteMessage(&request) 386 | } 387 | 388 | // SendBlock sends Block to peer 389 | func (p *Peer) SendBlock(block *consensus.Block) { 390 | logrus.Info("sending block, height: ", block.Header.Height) 391 | p.WriteMessage(block) 392 | } 393 | 394 | // SendPeerRequest sends peer request 395 | func (p *Peer) SendPeerRequest(capabilities consensus.Capabilities) { 396 | logrus.Infof("Sending GetPeerAddrs to %s", p.conn.RemoteAddr()) 397 | var request GetPeerAddrs 398 | 399 | request.Capabilities = capabilities 400 | 401 | p.WriteMessage(&request) 402 | } 403 | 404 | // SendHeaderRequest sends request headers 405 | func (p *Peer) SendHeaderRequest(locator consensus.Locator) { 406 | logrus.Info("sending headers request") 407 | 408 | if len(locator.Hashes) > consensus.MaxLocators { 409 | logrus.Debug("locator hashes count: ", len(locator.Hashes)) 410 | logrus.Fatal(errors.New("too big locator hashes")) 411 | } 412 | 413 | var request GetBlockHeaders 414 | request.Locator = locator 415 | 416 | p.WriteMessage(&request) 417 | } 418 | 419 | // SendTransaction sends tx to peer 420 | func (p *Peer) SendTransaction(tx consensus.Transaction) { 421 | logrus.Info("sending transaction") 422 | p.WriteMessage(&tx) 423 | } 424 | -------------------------------------------------------------------------------- /chain/chain.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package chain 6 | 7 | import ( 8 | "bytes" 9 | "errors" 10 | "github.com/dblokhin/gringo/consensus" 11 | "github.com/sirupsen/logrus" 12 | "sync" 13 | "time" 14 | ) 15 | 16 | // Testnet1 genesis block 17 | var Testnet1 = consensus.Block{ 18 | Header: consensus.BlockHeader{ 19 | Version: 1, 20 | Height: 0, 21 | Previous: bytes.Repeat([]byte{0xff}, consensus.BlockHashSize), 22 | Timestamp: time.Date(2017, 11, 16, 20, 0, 0, 0, time.UTC), 23 | TotalDifficulty: 10, 24 | 25 | UTXORoot: bytes.Repeat([]byte{0x00}, 32), 26 | RangeProofRoot: bytes.Repeat([]byte{0x00}, 32), 27 | KernelRoot: bytes.Repeat([]byte{0x00}, 32), 28 | 29 | Nonce: 28205, 30 | POW: consensus.Proof{ 31 | Nonces: []uint32{ 32 | 0x21e, 0x7a2, 0xeae, 0x144e, 0x1b1c, 0x1fbd, 33 | 0x203a, 0x214b, 0x293b, 0x2b74, 0x2bfa, 0x2c26, 34 | 0x32bb, 0x346a, 0x34c7, 0x37c5, 0x4164, 0x42cc, 35 | 0x4cc3, 0x55af, 0x5a70, 0x5b14, 0x5e1c, 0x5f76, 36 | 0x6061, 0x60f9, 0x61d7, 0x6318, 0x63a1, 0x63fb, 37 | 0x649b, 0x64e5, 0x65a1, 0x6b69, 0x70f8, 0x71c7, 38 | 0x71cd, 0x7492, 0x7b11, 0x7db8, 0x7f29, 0x7ff8, 39 | }, 40 | }, 41 | }, 42 | } 43 | 44 | // Testnet2 genesis block 45 | var Testnet2 = consensus.Block{ 46 | Header: consensus.BlockHeader{ 47 | Version: 1, 48 | Height: 0, 49 | Previous: bytes.Repeat([]byte{0xff}, consensus.BlockHashSize), 50 | Timestamp: time.Date(2017, 11, 16, 20, 0, 0, 0, time.UTC), 51 | //Difficulty: 10, 52 | //TotalDifficulty: 10, 53 | 54 | UTXORoot: bytes.Repeat([]byte{0x00}, 32), 55 | RangeProofRoot: bytes.Repeat([]byte{0x00}, 32), 56 | KernelRoot: bytes.Repeat([]byte{0x00}, 32), 57 | 58 | Nonce: 70081, 59 | POW: consensus.Proof{ 60 | Nonces: []uint32{ 61 | 0x43ee48, 0x18d5a49, 0x2b76803, 0x3181a29, 0x39d6a8a, 0x39ef8d8, 62 | 0x478a0fb, 0x69c1f9e, 0x6da4bca, 0x6f8782c, 0x9d842d7, 0xa051397, 63 | 0xb56934c, 0xbf1f2c7, 0xc992c89, 0xce53a5a, 0xfa87225, 0x1070f99e, 64 | 0x107b39af, 0x1160a11b, 0x11b379a8, 0x12420e02, 0x12991602, 0x12cc4a71, 65 | 0x13d91075, 0x15c950d0, 0x1659b7be, 0x1682c2b4, 0x1796c62f, 0x191cf4c9, 66 | 0x19d71ac0, 0x1b812e44, 0x1d150efe, 0x1d15bd77, 0x1d172841, 0x1d51e967, 67 | 0x1ee1de39, 0x1f35c9b3, 0x1f557204, 0x1fbf884f, 0x1fcf80bf, 0x1fd59d40, 68 | }, 69 | }, 70 | }, 71 | } 72 | 73 | // Testnet 3 initial block difficulty, moderately high, taking into account 74 | // a 30x Cuckoo adjustment factor 75 | const TESTNET3_INITIAL_DIFFICULTY = 30000 76 | 77 | var Testnet3 = consensus.Block{ 78 | Header: consensus.BlockHeader{ 79 | Version: 1, 80 | Height: 0, 81 | Previous: bytes.Repeat([]byte{0xff}, consensus.BlockHashSize), 82 | Timestamp: time.Date(2018, 7, 8, 18, 0, 0, 0, time.UTC), 83 | TotalDifficulty: TESTNET3_INITIAL_DIFFICULTY, 84 | 85 | UTXORoot: bytes.Repeat([]byte{0x00}, 32), 86 | RangeProofRoot: bytes.Repeat([]byte{0x00}, 32), 87 | KernelRoot: bytes.Repeat([]byte{0x00}, 32), 88 | 89 | TotalKernelOffset: bytes.Repeat([]byte{0x00}, 32), 90 | TotalKernelSum: bytes.Repeat([]byte{0x00}, 33), 91 | 92 | Nonce: 4956988373127691, 93 | POW: consensus.Proof{ 94 | EdgeBits: 30, 95 | Nonces: []uint32{ 96 | 0xa420dc, 0xc8ffee, 0x10e433e, 0x1de9428, 0x2ed4cea, 0x52d907b, 0x5af0e3f, 97 | 0x6b8fcae, 0x8319b53, 0x845ca8c, 0x8d2a13e, 0x8d6e4cc, 0x9349e8d, 0xa7a33c5, 98 | 0xaeac3cb, 0xb193e23, 0xb502e19, 0xb5d9804, 0xc9ac184, 0xd4f4de3, 0xd7a23b8, 99 | 0xf1d8660, 0xf443756, 0x10b833d2, 0x11418fc5, 0x11b8aeaf, 0x131836ec, 0x132ab818, 100 | 0x13a46a55, 0x13df89fe, 0x145d65b5, 0x166f9c3a, 0x166fe0ef, 0x178cb36f, 0x185baf68, 101 | 0x1bbfe563, 0x1bd637b4, 0x1cfc8382, 0x1d1ed012, 0x1e391ca5, 0x1e999b4c, 0x1f7c6d21, 102 | }, 103 | }, 104 | }, 105 | } 106 | 107 | const unitDifficulty = consensus.Difficulty( 108 | (2 << (consensus.SecondPowEdgeBits - consensus.BaseEdgeBits)) * 109 | uint64(consensus.SecondPowEdgeBits)) 110 | 111 | const testnet4InitialDifficulty = unitDifficulty * 1000000 112 | 113 | var Testnet4 = consensus.Block{ 114 | Header: consensus.BlockHeader{ 115 | Version: 1, 116 | Height: 0, 117 | Previous: bytes.Repeat([]byte{0xff}, consensus.BlockHashSize), 118 | Timestamp: time.Date(2018, 10, 17, 20, 0, 0, 0, time.UTC), 119 | TotalDifficulty: testnet4InitialDifficulty, 120 | 121 | UTXORoot: bytes.Repeat([]byte{0x00}, 32), 122 | RangeProofRoot: bytes.Repeat([]byte{0x00}, 32), 123 | KernelRoot: bytes.Repeat([]byte{0x00}, 32), 124 | 125 | TotalKernelOffset: bytes.Repeat([]byte{0x00}, 32), 126 | TotalKernelSum: bytes.Repeat([]byte{0x00}, 33), 127 | 128 | Nonce: 8612241555342799290, 129 | POW: consensus.Proof{ 130 | EdgeBits: 29, 131 | Nonces: []uint32{ 132 | 0x46f3b4, 0x1135f8c, 0x1a1596f, 0x1e10f71, 0x41c03ea, 0x63fe8e7, 0x65af34f, 133 | 0x73c16d3, 0x8216dc3, 0x9bc75d0, 0xae7d9ad, 0xc1cb12b, 0xc65e957, 0xf67a152, 134 | 0xfac6559, 0x100c3d71, 0x11eea08b, 0x1225dfbb, 0x124d61a1, 0x132a14b4, 0x13f4ec38, 135 | 0x1542d236, 0x155f2df0, 0x1577394e, 0x163c3513, 0x19349845, 0x19d46953, 0x19f65ed4, 136 | 0x1a0411b9, 0x1a2fa039, 0x1a72a06c, 0x1b02ddd2, 0x1b594d59, 0x1b7bffd3, 0x1befe12e, 137 | 0x1c82e4cd, 0x1d492478, 0x1de132a5, 0x1e578b3c, 0x1ed96855, 0x1f222896, 0x1fea0da6, 138 | }, 139 | }, 140 | }, 141 | } 142 | 143 | // Mainnet genesis block 144 | var Mainnet = consensus.Block{ 145 | Header: consensus.BlockHeader{ 146 | Version: 1, 147 | Height: 0, 148 | Previous: bytes.Repeat([]byte{0xff}, consensus.BlockHashSize), 149 | Timestamp: time.Date(2018, 8, 14, 0, 0, 0, 0, time.UTC), 150 | TotalDifficulty: 1000, 151 | 152 | UTXORoot: bytes.Repeat([]byte{0x00}, 32), 153 | RangeProofRoot: bytes.Repeat([]byte{0x00}, 32), 154 | KernelRoot: bytes.Repeat([]byte{0x00}, 32), 155 | 156 | Nonce: 28205, 157 | POW: consensus.Proof{ 158 | Nonces: []uint32{ 159 | 0x21e, 0x7a2, 0xeae, 0x144e, 0x1b1c, 0x1fbd, 160 | 0x203a, 0x214b, 0x293b, 0x2b74, 0x2bfa, 0x2c26, 161 | 0x32bb, 0x346a, 0x34c7, 0x37c5, 0x4164, 0x42cc, 162 | 0x4cc3, 0x55af, 0x5a70, 0x5b14, 0x5e1c, 0x5f76, 163 | 0x6061, 0x60f9, 0x61d7, 0x6318, 0x63a1, 0x63fb, 164 | 0x649b, 0x64e5, 0x65a1, 0x6b69, 0x70f8, 0x71c7, 165 | 0x71cd, 0x7492, 0x7b11, 0x7db8, 0x7f29, 0x7ff8, 166 | }, 167 | }, 168 | }, 169 | } 170 | 171 | type Chain struct { 172 | sync.RWMutex 173 | 174 | // Storage of blockchain 175 | storage Storage 176 | 177 | // genesis block 178 | genesis *consensus.Block 179 | // last block of blockchain 180 | head *consensus.Block 181 | // current height of chain 182 | height uint64 183 | // current total difficulty 184 | totalDifficulty consensus.Difficulty 185 | } 186 | 187 | func New(genesis *consensus.Block, storage Storage) *Chain { 188 | chain := Chain{ 189 | storage: storage, 190 | genesis: genesis, 191 | head: genesis, 192 | height: genesis.Header.Height, 193 | totalDifficulty: genesis.Header.TotalDifficulty, 194 | } 195 | 196 | // init state from storage 197 | // setting up currents: height, total diff & blockHashChain 198 | if lastBlock := storage.GetLastBlock(); lastBlock != nil { 199 | chain.head = lastBlock 200 | chain.totalDifficulty = lastBlock.Header.TotalDifficulty 201 | chain.height = lastBlock.Header.Height 202 | } 203 | 204 | return &chain 205 | } 206 | 207 | // Genesis returns genesis block 208 | func (c *Chain) Genesis() consensus.Block { 209 | return *c.genesis 210 | } 211 | 212 | // TotalDifficulty returns current total difficulty 213 | func (c *Chain) TotalDifficulty() consensus.Difficulty { 214 | return c.totalDifficulty 215 | } 216 | 217 | // Height returns current height 218 | func (c *Chain) Height() uint64 { 219 | return c.height 220 | } 221 | 222 | // GetBlockHeaders returns block headers 223 | func (c *Chain) GetBlockHeaders(loc consensus.Locator) []consensus.BlockHeader { 224 | // for safety 225 | if len(loc.Hashes) > consensus.MaxLocators { 226 | logrus.Error("locator hashes object is too big") 227 | loc.Hashes = loc.Hashes[:consensus.MaxLocators] 228 | } 229 | 230 | result := make([]consensus.BlockHeader, 0) 231 | c.RLock() 232 | defer c.RUnlock() 233 | 234 | for _, hash := range loc.Hashes { 235 | 236 | // if hash is head of current chain, return empty result 237 | if bytes.Compare(hash, c.head.Hash()) == 0 { 238 | return result 239 | } 240 | 241 | blockID := consensus.BlockID{ 242 | Hash: hash, 243 | Height: nil, 244 | } 245 | 246 | // get blocks from 247 | blockList := c.storage.From(blockID, consensus.MaxBlockHeaders+1) 248 | if len(blockList) > 0 { 249 | // pass first block 250 | blockList = blockList[1:] 251 | 252 | // collect headers 253 | for _, block := range blockList { 254 | result = append(result, block.Header) 255 | } 256 | 257 | return result 258 | } 259 | } 260 | 261 | return result 262 | } 263 | 264 | // GetBlock returns block by hash, if not found returns nil, nil 265 | func (c *Chain) GetBlock(hash consensus.Hash) *consensus.Block { 266 | if hash == nil { 267 | return nil 268 | } 269 | 270 | return c.storage.GetBlock(consensus.BlockID{ 271 | Hash: hash, 272 | Height: nil, 273 | }) 274 | } 275 | 276 | // GetBlockID returns block by hash, height or both 277 | func (c *Chain) GetBlockID(b consensus.BlockID) *consensus.Block { 278 | return c.storage.GetBlock(b) 279 | } 280 | 281 | func (c *Chain) ProcessHeaders(headers []consensus.BlockHeader) error { 282 | for _, header := range headers { 283 | if err := header.Validate(); err != nil { 284 | return err 285 | } 286 | } 287 | return nil 288 | } 289 | 290 | func (c *Chain) ProcessBlock(block *consensus.Block) error { 291 | // before locking storage on change MUST lock the Chain 292 | // Checking existing block 293 | c.Lock() 294 | defer c.Unlock() 295 | logrus.Infof("processing block (height: %d, totalDiff: %d)", block.Header.Height, block.Header.TotalDifficulty) 296 | 297 | // quick check is it current tip 298 | if bytes.Compare(c.head.Hash(), block.Hash()) == 0 { 299 | // the block is exists 300 | return nil 301 | } 302 | 303 | // verify block by consensus rules 304 | if err := block.Validate(); err != nil { 305 | return err 306 | } 307 | 308 | logrus.Info("getting the previous blocks") 309 | // Get the previous block 310 | prevHeight := block.Header.Height - 1 311 | prevBlockID := consensus.BlockID{ 312 | Hash: block.Header.Previous, 313 | Height: &prevHeight, 314 | } 315 | prevBlock := c.storage.GetBlock(prevBlockID) 316 | if prevBlock == nil { 317 | logrus.Info("no previous blocks") 318 | // No previous block at the current chain 319 | // It may be unknown fork-chain 320 | // TODO: process that 321 | return nil 322 | } 323 | 324 | logrus.Info("validating with the previous blocks") 325 | // Previous block exists 326 | 327 | // Checks with the previous block 328 | // - previous Timestamp MUST BE less block.Header.Timestamp 329 | if !block.Header.Timestamp.After(prevBlock.Header.Timestamp) { 330 | return errors.New("invalid block time") 331 | } 332 | // - block.TotalDiff MUST BE == previous.TotalDiff + previous.POW.ToDifficulty() 333 | if block.Header.TotalDifficulty != prevBlock.Header.TotalDifficulty+prevBlock.Header.POW.ToDifficulty() { 334 | return errors.New("wrong block total difficulty") 335 | } 336 | // - check that the difficulty is not less than that calculated by the 337 | // difficulty average based on the previous blocks 338 | limit := int(consensus.DifficultyAdjustWindow + consensus.MedianTimeWindow) 339 | fromHeight := uint64(0) 340 | if block.Header.Height > uint64(limit) { 341 | fromHeight = block.Header.Height - uint64(limit) 342 | } 343 | 344 | blockID := consensus.BlockID{ 345 | Hash: nil, 346 | Height: &fromHeight, 347 | } 348 | 349 | diffAvg := consensus.NextDifficulty(c.storage.From(blockID, limit)) 350 | if block.Header.Difficulty < diffAvg { 351 | return errors.New("difficulty is too low") 352 | } 353 | 354 | // TODO: applying block 355 | 356 | return nil 357 | } 358 | 359 | // Head returns lastest block in blockchain 360 | func (c *Chain) Head() consensus.Block { 361 | return *c.head 362 | } 363 | 364 | // Validate returns nil if chain successfully passed consensus rules 365 | func (c *Chain) Validate() error { 366 | c.Lock() 367 | defer c.Unlock() 368 | 369 | block := c.head 370 | 371 | // go from head to genesis 372 | // TODO: MUST check all consensus rules 373 | for bytes.Compare(block.Header.Previous, c.genesis.Hash()) != 0 { 374 | err := block.Validate() 375 | if err == nil { 376 | return err 377 | } 378 | 379 | if block = c.GetBlock(block.Header.Previous); block == nil { 380 | return errors.New("invalid previous hash. blockchain integrity is broken") 381 | } 382 | 383 | // TODO: check other rules, may be checking block.Height? 384 | } 385 | 386 | return nil 387 | } 388 | -------------------------------------------------------------------------------- /docs/papers/OriginalWhitePaper.txt: -------------------------------------------------------------------------------- 1 | 2 | MIMBLEWIMBLE 3 | Tom Elvis Jedusor 4 | 19 July, 2016 5 | 6 | \****/ 7 | Introduction 8 | /****\ 9 | 10 | Bitcoin is the first widely used financial system for which all the necessary 11 | data to validate the system status can be cryptographically verified by anyone. 12 | However, it accomplishes this feat by storing all transactions in a public 13 | database called "the blockchain" and someone who genuinely wishes to check 14 | this state must download the whole thing and basically replay each transaction, 15 | check each one as they go. Meanwhile, most of these transactions have not 16 | affected the actual final state (they create outputs that are destroyed 17 | a transaction later). 18 | 19 | At the time of this writing, there were nearly 150 million transactions 20 | committed in the blockchain, which must be replayed to produce a set of 21 | only 4 million unspent outputs. 22 | 23 | It would be better if an auditor needed only to check data on the outputs 24 | themselves, but this is impossible because they are valid if and only if the 25 | output is at the end of a chain of previous outputs, each signs the next. In 26 | other words, the whole blockchain must be validated to confirm the final 27 | state. 28 | 29 | 30 | Add to this that these transactions are cryptographically atomic, it is clear 31 | what outputs go into every transaction and what emerges. The "transaction graph" 32 | resulting reveals a lot of information and is subjected to analysis by many 33 | companies whose business model is to monitor and control the lower classes. 34 | This makes it very non-private and even dangerous for people to use. 35 | 36 | 37 | Some solutions to this have been proposed. Greg Maxwell discovered to encrypt 38 | the amounts, so that the graph of the transaction is faceless but still allow 39 | validation that the sums are correct [1]. Dr Maxwell also produced CoinJoin, 40 | a system for Bitcoin users to combine interactively transactions, confusing 41 | the transaction graph. Nicolas van Saberhagen has developed a system to blind 42 | the transaction entries, goes much further to cloud the transaction graph (as 43 | well as not needed the user interaction) [3]. Later, Shen Noether combined 44 | the two approaches to obtain "confidential transactions" of Maxwell AND the 45 | darkening of van Saberhagen [4]. 46 | 47 | These solutions are very good and would make Bitcoin very safe to use. But 48 | the problem of too much data is made even worse. Confidential transactions 49 | require multi-kilobyte proofs on every output, and van Saberhagen signatures 50 | require every output to be stored for ever, since it is not possible to tell 51 | when they are truly spent. 52 | 53 | Dr. Maxwell's CoinJoin has the problem of needing interactivity. Dr. Yuan Horas 54 | Mouton fixed this by making transactions freely mergeable [5], but he needed to 55 | use pairing-based cryptography, which is potentially slower and more difficult 56 | to trust. He called this "one-way aggregate signatures" (OWAS). 57 | 58 | OWAS had the good idea to combine the transactions in blocks. Imagine that we 59 | can combine across blocks (perhaps with some glue data) so that when the outputs 60 | are created and destroyed, it is the same as if they never existed. Then, to 61 | validate the entire chain, users only need to know when money is entered into 62 | the system (new money in each block as in Bitcoin or Monero or peg-ins for 63 | sidechains [6]) and final unspent outputs, the rest can be removed and forgotten. 64 | Then we can have Confidential Transactions to hide the amounts and OWAS to blur 65 | the transaction graph, and use LESS space than Bitcoin to allow users to fully 66 | verify the blockchain. And also imagine that we must not pairing-based cryptography 67 | or new hypotheses, just regular discrete logarithms signatures like Bitcoin. 68 | Here is what I propose. 69 | 70 | I call my creation Mimblewimble because it is used to prevent the blockchain from 71 | talking about all user's information [7]. 72 | 73 | 74 | \****/ 75 | Confidential Transactions and OWAS 76 | /****\ 77 | 78 | The first thing we need to do is remove Bitcoin Script. This is sad, but it is too 79 | powerful so it is impossible to merge transactions using general scripts. We will 80 | demonstrate that confidential transactions of Dr. Maxwell are enough (after some 81 | small modification) to authorize spending of outputs and also allows to make 82 | combined transactions without interaction. This is in fact identical to OWAS, 83 | and allows relaying nodes take some transaction fee or the recipient to change 84 | the transaction fees. These additional things Bitcoin can not do, we get for free. 85 | 86 | We start by reminding the reader how confidential transactions work. First, the 87 | amounts are coded by the following equation: 88 | 89 | C = r*G + v*H 90 | 91 | where C is a Pedersen commitment, G and H are fixed nothing-up-my-sleeve elliptic 92 | curve group generators, v is the amount, and r is a secret random blinding key. 93 | 94 | Attached to this output is a rangeproof which proves that v is in [0, 2^64], so 95 | that user cannot exploit the blinding to produce overflow attacks, etc. 96 | 97 | To validate a transaction, the verifer will add commitments for all outputs, plus 98 | f*H (f here is the transaction fee which is given explicitly) and subtracts all 99 | input commitments. The result must be 0, which proves that no amount was created 100 | or destroyed overall. 101 | 102 | We note that to create such a transaction, the user must know the sum of all the 103 | values of r for commitments entries. Therefore, the r-values (and their sums) act 104 | as secret keys. If we can make the r output values known only to the recipient, 105 | then we have an authentication system! Unfortunately, if we keep the rule that 106 | commits all add to 0, this is impossible, because the sender knows the sum of 107 | all _his_ r values, and therefore knows the receipient's r values sum to the 108 | negative of that. So instead, we allow the transaction to sum to a nonzero value 109 | k*G, and require a signature of an empty string with this as key, to prove its 110 | amount component is zero. 111 | 112 | We let transactions have as many k*G values as they want, each with a signature, 113 | and sum them during verification. 114 | 115 | To create transactions sender and recipient do following ritual: 116 | 117 | 1. Sender and recipient agree on amount to be sent. Call this b. 118 | 119 | 2. Sender creates transaction with all inputs and change output(s), and gives 120 | recipient the total blinding factor (r-value of change minus r-values of 121 | inputs) along with this transaction. So the commitments sum to r*G - b*H. 122 | 123 | 3. Recipient chooses random r-values for his outputs, and values that sum 124 | to b minus fee, and adds these to transaction (including range proof). 125 | Now the commitments sum to k*G - fee*H for some k that only recipient 126 | knows. 127 | 128 | 4. Recipient attaches signature with k to the transaction, and the explicit 129 | fee. It has done. 130 | 131 | Now, creating transactions in this manner supports OWAS already. To show this, 132 | suppose we have two transactions that have a surplus k1*G and k2*G, and the 133 | attached signatures with these. Then you can combine the lists of inputs and 134 | outputs of the two transactions, with both k1*G and k2*G to the mix, and 135 | voilá! is again a valid transaction. From the combination, it is impossible to 136 | say which outputs or inputs are from which original transaction. 137 | 138 | Because of this, we change our block format from Bitcoin to this information: 139 | 140 | 1. Explicit amounts for new money (block subsidy or sidechain peg-ins) with 141 | whatever else data this needs. For a sidechain peg-in maybe it references 142 | a Bitcoin transaction that commits to a specific excess k*G value? 143 | 144 | 2. Inputs of all transactions 145 | 146 | 3. Outputs of all transactions 147 | 148 | 4. Excess k*G values for all transactions 149 | 150 | Each of these are grouped together because it do not matter what the transaction 151 | boundaries are originally. In addition, Lists 2 3 and 4 should be required to be 152 | coded in alphabetical order, since it is quick to check and prevents the block 153 | creator of leaking any information about the original transactions. 154 | 155 | Note that the outputs are now identified by their hash, and not by their position 156 | in a transaction that could easily change. Therefore, it should be banned to have 157 | two unspent outputs are equal at the same time, to avoid confusion. 158 | 159 | 160 | 161 | \****/ 162 | Merging Transactions Across Blocks 163 | /****\ 164 | 165 | Now, we have used Dr. Maxwell's Confidential Transactions to create a noninteractive 166 | version of Dr. Maxwell's CoinJoin, but we have not seen the last of marvelous Dr. Maxwell! 167 | We need another idea, transaction cut-through, he described in [8]. Again, we create a 168 | noninteractive version of this, and to show how it is used with several blocks. 169 | 170 | We can imagine now each block as one large transaction. To validate it, we add all the 171 | output commitments together, then subtracts all input commitments, k*G values, and all 172 | explicit input amounts times H. We find that we could combine transactions from two 173 | blocks, as we combined transactions to form a single block, and the result is again 174 | a valid transaction. Except now, some output commitments have an input commitment exactly 175 | equal to it, where the first block's output was spent in the second block. We could 176 | remove both commitments and still have a valid transaction. In fact, there is not even 177 | need to check the rangeproof of the deleted output. 178 | 179 | The extension of this idea all the way from the genesis block to the latest block, we 180 | see that EVERY nonexplicit input is deleted along with its referenced output. What 181 | remains are only the unspent outputs, explicit input amounts and every k*G value. 182 | And this whole mess can be validated as if it were one transaction: add all unspent 183 | commitments output, subtract the values k*G, validate explicit input amounts (if there 184 | is anything to validate) then subtract them times H. If the sum is 0, the entire 185 | chain is good. 186 | 187 | What is this mean? When a user starts up and downloads the chain he needs the following 188 | data from each block: 189 | 190 | 1. Explicit amounts for new money (block subsidy or sidechain peg-ins) with 191 | whatever else data this needs. 192 | 193 | 2. Unspent outputs of all transactions, along with a merkle proof that each 194 | output appeared in the original block. 195 | 196 | 3. Excess k*G values for all transactions. 197 | 198 | Bitcoin today there are about 423000 blocks, totaling 80GB or so of data on the hard 199 | drive to validate everything. These data are about 150 million transactions and 5 million 200 | unspent nonconfidential outputs. Estimate how much space the number of transactions 201 | take on a Mimblewimble chain. Each unspent output is around 3Kb for rangeproof and 202 | Merkle proof. Each transaction also adds about 100 bytes: a k*G value and a signature. 203 | The block headers and explicit amounts are negligible. Add this together and get 204 | 30Gb -- with a confidential transaction and obscured transaction graph! 205 | 206 | 207 | \****/ 208 | Questions and Intuition 209 | /****\ 210 | 211 | Here are some questions that since these weeks, dreams asked me and I woke up sweating. 212 | But in fact it is OK. 213 | 214 | Q. If you delete the transaction outputs, user cannot verify the rangeproof and maybe 215 | a negative amount is created. 216 | 217 | A. This is OK. For the entire transaction to validate all negative amounts must have 218 | been destroyed. User have SPV security only that no illegal inflation happened in 219 | the past, but the user knows that _at this time_ no inflation occurred. 220 | 221 | 222 | Q. If you delete the inputs, double spending can happen. 223 | 224 | A. In fact, this means: maybe someone claims that some unspent output was spent 225 | in the old days. But this is impossible, otherwise the sum of the combined transaction 226 | could not be zero. 227 | 228 | An exception is that if the outputs are amount zero, it is possible to make two that 229 | are negatives of each other, and the pair can be revived without anything breaks. So to 230 | prevent consensus problems, outputs 0-amount should be banned. Just add H at each output, 231 | now they all amount to at least 1. 232 | 233 | 234 | 235 | \****/ 236 | Future Research 237 | /****\ 238 | 239 | Here are some questions I can not answer at the time of this writing. 240 | 241 | 1. What script support is possible? We would need to translate script operations into 242 | some sort of discrete logarithm information. 243 | 244 | 2. We require user to check all k*G values, when in fact all that is needed is that their 245 | sum is of the form k*G. Instead of using signatures is there another proof of discrete 246 | logarithm that could be combined? 247 | 248 | 3. There is a denial-of-service option when a user downloads the chain, the peer can give 249 | gigabytes of data and list the wrong unspent outputs. The user will see that the result 250 | do not add up to 0, but cannot tell where the problem is. 251 | 252 | For now maybe the user should just download the blockchain from a Torrent or something 253 | where the data is shared between many users and is reasonably likely to be correct. 254 | 255 | 256 | 257 | [1] https://people.xiph.org/~greg/confidential_values.txt 258 | [2] https://bitcointalk.org/index.php?topic=279249.0 259 | [3] https://cryptonote.org/whitepaper.pdf 260 | [4] https://eprint.iacr.org/2015/1098.pdf 261 | [5] https://download.wpsoftware.net/bitcoin/wizardry/horasyuanmouton-owas.pdf 262 | [6] http://blockstream.com/sidechains.pdf 263 | [7] http://fr.harrypotter.wikia.com/wiki/Sortilège_de_Langue_de_Plomb 264 | [8] https://bitcointalk.org/index.php?topic=281848.0 265 | 266 | -------------------------------------------------------------------------------- /consensus/block.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Gringo Developers. All rights reserved. 2 | // Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v3 3 | // license that can be found in the LICENSE file. 4 | 5 | package consensus 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "errors" 11 | "fmt" 12 | "github.com/dblokhin/gringo/secp256k1zkp" 13 | "github.com/sirupsen/logrus" 14 | "github.com/yoss22/bulletproofs" 15 | "golang.org/x/crypto/blake2b" 16 | "io" 17 | "sort" 18 | "time" 19 | ) 20 | 21 | // SwitchCommitHashSize The size to use for the stored blake2 hash of a switch_commitment 22 | const SwitchCommitHashSize = 20 23 | 24 | // OutputFeatures is options for block validation 25 | type OutputFeatures uint8 26 | 27 | const ( 28 | // No flags 29 | DefaultOutput OutputFeatures = 0 30 | // Output is a coinbase output, must not be spent until maturity 31 | CoinbaseOutput OutputFeatures = 1 << 0 32 | ) 33 | 34 | func (f OutputFeatures) String() string { 35 | switch f { 36 | case DefaultOutput: 37 | return "" 38 | case CoinbaseOutput: 39 | return "Coinbase" 40 | } 41 | return "" 42 | } 43 | 44 | // KernelFeatures is options for a kernel's structure or use 45 | type KernelFeatures uint8 46 | 47 | const ( 48 | // No flags 49 | DefaultKernel KernelFeatures = 0 50 | // Kernel matching a coinbase output 51 | CoinbaseKernel KernelFeatures = 1 << 0 52 | ) 53 | 54 | func (f KernelFeatures) String() string { 55 | switch f { 56 | case DefaultKernel: 57 | return "" 58 | case CoinbaseKernel: 59 | return "Coinbase" 60 | } 61 | return "" 62 | } 63 | 64 | // BlockID identify block by Hash or/and Height (if not nill) 65 | type BlockID struct { 66 | // Block hash, if nil - use the height 67 | Hash Hash 68 | // Block height, if nil - use the hash 69 | Height *uint64 70 | } 71 | 72 | // Block of grin blockchain 73 | type Block struct { 74 | Header BlockHeader 75 | 76 | Inputs InputList 77 | Outputs OutputList 78 | Kernels TxKernelList 79 | } 80 | 81 | // Bytes implements p2p Message interface 82 | func (b *Block) Bytes() []byte { 83 | buff := new(bytes.Buffer) 84 | if _, err := buff.Write(b.Header.Bytes()); err != nil { 85 | logrus.Fatal(err) 86 | } 87 | 88 | // Write counts: inputs, outputs, kernels 89 | if err := binary.Write(buff, binary.BigEndian, uint64(len(b.Inputs))); err != nil { 90 | logrus.Fatal(err) 91 | } 92 | 93 | if err := binary.Write(buff, binary.BigEndian, uint64(len(b.Outputs))); err != nil { 94 | logrus.Fatal(err) 95 | } 96 | 97 | if err := binary.Write(buff, binary.BigEndian, uint64(len(b.Kernels))); err != nil { 98 | logrus.Fatal(err) 99 | } 100 | 101 | // consensus rule: input, output, kernels MUST BE sorted! 102 | sort.Sort(b.Inputs) 103 | sort.Sort(b.Outputs) 104 | sort.Sort(b.Kernels) 105 | 106 | // Write inputs 107 | for _, input := range b.Inputs { 108 | if _, err := buff.Write(input.Bytes()); err != nil { 109 | logrus.Fatal(err) 110 | } 111 | } 112 | 113 | // Write outputs 114 | for _, output := range b.Outputs { 115 | if _, err := buff.Write(output.Bytes()); err != nil { 116 | logrus.Fatal(err) 117 | } 118 | } 119 | 120 | // Write kernels 121 | for _, txKernel := range b.Kernels { 122 | if _, err := buff.Write(txKernel.Bytes()); err != nil { 123 | logrus.Fatal(err) 124 | } 125 | } 126 | 127 | return buff.Bytes() 128 | } 129 | 130 | // Type implements p2p Message interface 131 | func (b *Block) Type() uint8 { 132 | return MsgTypeBlock 133 | } 134 | 135 | // Read implements p2p Message interface 136 | func (b *Block) Read(r io.Reader) error { 137 | // Read block header 138 | if err := b.Header.Read(r); err != nil { 139 | return err 140 | } 141 | 142 | // Read counts 143 | var inputs, outputs, kernels uint64 144 | if err := binary.Read(r, binary.BigEndian, &inputs); err != nil { 145 | return err 146 | } 147 | 148 | if err := binary.Read(r, binary.BigEndian, &outputs); err != nil { 149 | return err 150 | } 151 | 152 | if err := binary.Read(r, binary.BigEndian, &kernels); err != nil { 153 | return err 154 | } 155 | 156 | // Sanity check the lengths. 157 | if inputs > 1000000 { 158 | return errors.New("transaction contains too many inputs") 159 | } 160 | if outputs > 1000000 { 161 | return errors.New("transaction contains too many outputs") 162 | } 163 | if kernels > 1000000 { 164 | return errors.New("transaction contains too many kernels") 165 | } 166 | 167 | // Read inputs 168 | b.Inputs = make([]Input, inputs) 169 | for i := uint64(0); i < inputs; i++ { 170 | if err := b.Inputs[i].Read(r); err != nil { 171 | return err 172 | } 173 | } 174 | 175 | // Read outputs 176 | b.Outputs = make([]Output, outputs) 177 | for i := uint64(0); i < outputs; i++ { 178 | if err := b.Outputs[i].Read(r); err != nil { 179 | return err 180 | } 181 | } 182 | 183 | // Read kernels 184 | b.Kernels = make([]TxKernel, kernels) 185 | for i := uint64(0); i < kernels; i++ { 186 | if err := b.Kernels[i].Read(r); err != nil { 187 | return err 188 | } 189 | } 190 | 191 | return nil 192 | } 193 | 194 | // String implements String() interface 195 | func (p Block) String() string { 196 | return fmt.Sprintf("%#v", p) 197 | } 198 | 199 | // Hash returns hash of block 200 | func (b *Block) Hash() Hash { 201 | return b.Header.Hash() 202 | } 203 | 204 | // Validate returns nil if block successfully passed BLOCK-SCOPE consensus rules 205 | func (b *Block) Validate() error { 206 | logrus.Info("block scope validate") 207 | /* 208 | TODO: implement it: 209 | 210 | verify_weight() 211 | verify_sorted() 212 | verify_coinbase() 213 | verify_kernels() 214 | 215 | */ 216 | 217 | // Validate header and proof-of-work. 218 | if err := b.Header.Validate(); err != nil { 219 | return err 220 | } 221 | 222 | // Check that consensus rule MaxBlockCoinbaseOutputs & MaxBlockCoinbaseKernels 223 | if len(b.Outputs) == 0 || len(b.Kernels) == 0 { 224 | return errors.New("invalid nocoinbase block") 225 | } 226 | 227 | // Check sorted inputs, outputs, kernels 228 | if err := b.verifySorted(); err != nil { 229 | return err 230 | } 231 | 232 | if err := b.verifyCoinbase(); err != nil { 233 | return err 234 | } 235 | 236 | // Verify all output values are within the correct range. 237 | if err := b.verifyRangeProofs(); err != nil { 238 | return err 239 | } 240 | 241 | if err := b.verifyKernels(); err != nil { 242 | return err 243 | } 244 | 245 | return nil 246 | } 247 | 248 | func (b *Block) verifyCoinbase() error { 249 | coinbase := 0 250 | 251 | for _, output := range b.Outputs { 252 | if output.Features&CoinbaseOutput == CoinbaseOutput { 253 | coinbase++ 254 | 255 | if coinbase > MaxBlockCoinbaseOutputs { 256 | return errors.New("invalid block with few coinbase outputs") 257 | } 258 | 259 | // Validate output 260 | if err := output.Validate(); err != nil { 261 | return err 262 | } 263 | } 264 | } 265 | 266 | // Check the roots 267 | // TODO: do that 268 | 269 | return nil 270 | } 271 | 272 | func (b *Block) verifyKernels() error { 273 | coinbase := 0 274 | 275 | for _, kernel := range b.Kernels { 276 | if kernel.Features&CoinbaseKernel == CoinbaseKernel { 277 | coinbase++ 278 | 279 | if coinbase > MaxBlockCoinbaseKernels { 280 | return errors.New("invalid block with few coinbase kernels") 281 | } 282 | 283 | // Validate kernel 284 | if err := kernel.Validate(); err != nil { 285 | return err 286 | } 287 | } 288 | } 289 | 290 | // TODO: Verify that the kernel sums are correct. 291 | 292 | // Check the roots 293 | // TODO: do that 294 | 295 | return nil 296 | } 297 | 298 | // verifySorted checks sorted inputs, outputs, kernels 299 | func (b *Block) verifySorted() error { 300 | if !sort.IsSorted(b.Inputs) { 301 | return errors.New("block inputs are not sorted") 302 | } 303 | 304 | if !sort.IsSorted(b.Outputs) { 305 | return errors.New("block outputs are not sorted") 306 | } 307 | 308 | if !sort.IsSorted(b.Kernels) { 309 | return errors.New("block kernels are not sorted") 310 | } 311 | 312 | return nil 313 | } 314 | 315 | // verifyRangeProofs returns nil if all outputs have valid range proofs. 316 | func (b *Block) verifyRangeProofs() error { 317 | // TODO(yoss22): Batch verify these. 318 | prover := bulletproofs.NewProver(64) 319 | for _, output := range b.Outputs { 320 | if !prover.Verify(output.Commit, output.RangeProof) { 321 | return fmt.Errorf("proof verification failed for %v %v", 322 | output.Commit, output.RangeProof) 323 | } 324 | } 325 | return nil 326 | } 327 | 328 | // CompactBlock compact version of grin block 329 | // Compact representation of a full block. 330 | // Each input/output/kernel is represented as a short_id. 331 | // A node is reasonably likely to have already seen all tx data (tx broadcast before block) 332 | // and can go request missing tx data from peers if necessary to hydrate a compact block 333 | // into a full block. 334 | type CompactBlock struct { 335 | // The header with metadata and commitments to the rest of the data 336 | Header BlockHeader 337 | // List of full outputs - specifically the coinbase output(s) 338 | Outputs OutputList 339 | // List of full kernels - specifically the coinbase kernel(s) 340 | Kernels TxKernelList 341 | // List of transaction kernels, excluding those in the full list (short_ids) 342 | KernelIDs ShortIDList 343 | } 344 | 345 | // Bytes implements p2p Message interface 346 | func (b *CompactBlock) Bytes() []byte { 347 | buff := new(bytes.Buffer) 348 | if _, err := buff.Write(b.Header.Bytes()); err != nil { 349 | logrus.Fatal(err) 350 | } 351 | 352 | if err := binary.Write(buff, binary.BigEndian, uint8(len(b.Outputs))); err != nil { 353 | logrus.Fatal(err) 354 | } 355 | 356 | if err := binary.Write(buff, binary.BigEndian, uint8(len(b.Kernels))); err != nil { 357 | logrus.Fatal(err) 358 | } 359 | 360 | if err := binary.Write(buff, binary.BigEndian, uint64(len(b.KernelIDs))); err != nil { 361 | logrus.Fatal(err) 362 | } 363 | 364 | // consensus rule: input, output, kernels MUST BE sorted! 365 | sort.Sort(b.Outputs) 366 | sort.Sort(b.Kernels) 367 | sort.Sort(b.KernelIDs) 368 | 369 | // Write outputs 370 | for _, output := range b.Outputs { 371 | if _, err := buff.Write(output.Bytes()); err != nil { 372 | logrus.Fatal(err) 373 | } 374 | } 375 | 376 | // Write kernels 377 | for _, txKernel := range b.Kernels { 378 | if _, err := buff.Write(txKernel.Bytes()); err != nil { 379 | logrus.Fatal(err) 380 | } 381 | } 382 | 383 | // Write kernels ids 384 | for _, id := range b.KernelIDs { 385 | if _, err := buff.Write(id); err != nil { 386 | logrus.Fatal(err) 387 | } 388 | } 389 | 390 | return buff.Bytes() 391 | } 392 | 393 | // Type implements p2p Message interface 394 | func (b *CompactBlock) Type() uint8 { 395 | return MsgTypeCompactBlock 396 | } 397 | 398 | // Read implements p2p Message interface 399 | func (b *CompactBlock) Read(r io.Reader) error { 400 | // Read block header 401 | if err := b.Header.Read(r); err != nil { 402 | return err 403 | } 404 | 405 | // Read counts 406 | var ( 407 | outputs, kernels uint8 408 | kernelIDs uint64 409 | ) 410 | 411 | if err := binary.Read(r, binary.BigEndian, &outputs); err != nil { 412 | return err 413 | } 414 | 415 | if err := binary.Read(r, binary.BigEndian, &kernels); err != nil { 416 | return err 417 | } 418 | 419 | if err := binary.Read(r, binary.BigEndian, &kernelIDs); err != nil { 420 | return err 421 | } 422 | 423 | // Read outputs 424 | b.Outputs = make(OutputList, outputs) 425 | for i := uint8(0); i < outputs; i++ { 426 | if err := b.Outputs[i].Read(r); err != nil { 427 | return err 428 | } 429 | } 430 | 431 | // Read kernels 432 | b.Kernels = make(TxKernelList, kernels) 433 | for i := uint8(0); i < kernels; i++ { 434 | 435 | if err := b.Kernels[i].Read(r); err != nil { 436 | return err 437 | } 438 | } 439 | 440 | // Read kernels ids 441 | b.KernelIDs = make(ShortIDList, kernelIDs) 442 | for i := uint64(0); i < kernelIDs; i++ { 443 | 444 | shortID := make(ShortID, ShortIDSize) 445 | if _, err := io.ReadFull(r, shortID); err != nil { 446 | return err 447 | } 448 | 449 | b.KernelIDs[i] = shortID 450 | } 451 | 452 | return nil 453 | } 454 | 455 | // String implements String() interface 456 | func (p CompactBlock) String() string { 457 | return fmt.Sprintf("%#v", p) 458 | } 459 | 460 | // Hash returns hash of block 461 | func (b *CompactBlock) Hash() Hash { 462 | return b.Header.Hash() 463 | } 464 | 465 | type BlockList []Block 466 | 467 | type Input struct { 468 | Features OutputFeatures 469 | Commit secp256k1zkp.Commitment 470 | } 471 | 472 | func (input *Input) Bytes() []byte { 473 | buff := new(bytes.Buffer) 474 | 475 | if err := binary.Write(buff, binary.BigEndian, uint8(input.Features)); err != nil { 476 | logrus.Fatal(err) 477 | } 478 | 479 | if _, err := buff.Write(input.Commit); err != nil { 480 | logrus.Fatal(err) 481 | } 482 | 483 | return buff.Bytes() 484 | } 485 | 486 | func (input *Input) Read(r io.Reader) error { 487 | if err := binary.Read(r, binary.BigEndian, &input.Features); err != nil { 488 | return err 489 | } 490 | 491 | commitment := make([]byte, secp256k1zkp.PedersenCommitmentSize) 492 | if _, err := io.ReadFull(r, commitment); err != nil { 493 | return err 494 | } 495 | 496 | input.Commit = commitment 497 | 498 | return nil 499 | } 500 | 501 | // Hash returns a hash of the serialised input. 502 | func (input *Input) Hash() []byte { 503 | hashed := blake2b.Sum256(input.Bytes()) 504 | return hashed[:] 505 | } 506 | 507 | // InputList sortable list of inputs 508 | type InputList []Input 509 | 510 | func (m InputList) Len() int { 511 | return len(m) 512 | } 513 | 514 | // Less is used to order inputs by their hash. 515 | func (m InputList) Less(i, j int) bool { 516 | return bytes.Compare(m[i].Hash(), m[j].Hash()) < 0 517 | } 518 | 519 | func (m InputList) Swap(i, j int) { 520 | m[i], m[j] = m[j], m[i] 521 | } 522 | 523 | // Output for a transaction, defining the new ownership of coins that are being 524 | // transferred. The commitment is a blinded value for the output while the 525 | // range proof guarantees the commitment includes a positive value without 526 | // overflow and the ownership of the private key. The switch commitment hash 527 | // provides future-proofing against quantum-based attacks, as well as provides 528 | // wallet implementations with a way to identify their outputs for wallet 529 | // reconstruction 530 | // 531 | // The hash of an output only covers its features, lock_height, commitment, 532 | // and switch commitment. The range proof is expected to have its own hash 533 | // and is stored and committed to separately. 534 | type Output struct { 535 | // Options for an output's structure or use 536 | Features OutputFeatures 537 | // The homomorphic commitment representing the output's amount 538 | Commit *bulletproofs.Point 539 | // A proof that the commitment is in the right range 540 | RangeProof bulletproofs.BulletProof 541 | } 542 | 543 | func (o *Output) BytesWithoutProof() []byte { 544 | buff := new(bytes.Buffer) 545 | 546 | // Write features 547 | if err := binary.Write(buff, binary.BigEndian, uint8(o.Features)); err != nil { 548 | logrus.Fatal(err) 549 | } 550 | 551 | if _, err := buff.Write(o.Commit.Bytes()); err != nil { 552 | logrus.Fatal(err) 553 | } 554 | 555 | return buff.Bytes() 556 | } 557 | 558 | // Bytes implements p2p Message interface 559 | func (o *Output) Bytes() []byte { 560 | buff := new(bytes.Buffer) 561 | 562 | if _, err := buff.Write(o.BytesWithoutProof()); err != nil { 563 | logrus.Fatal(err) 564 | } 565 | 566 | proof := o.RangeProof.Bytes() 567 | 568 | if err := binary.Write(buff, binary.BigEndian, uint64(len(proof))); err != nil { 569 | logrus.Fatal(err) 570 | } 571 | 572 | if _, err := buff.Write(proof); err != nil { 573 | logrus.Fatal(err) 574 | } 575 | 576 | return buff.Bytes() 577 | } 578 | 579 | // Read implements p2p Message interface 580 | func (o *Output) Read(r io.Reader) error { 581 | // Read features 582 | if err := binary.Read(r, binary.BigEndian, (*uint8)(&o.Features)); err != nil { 583 | return err 584 | } 585 | 586 | // Read commitment 587 | o.Commit = new(bulletproofs.Point) 588 | if err := o.Commit.Read(r); err != nil { 589 | return err 590 | } 591 | 592 | // Read range proof 593 | var proofLen uint64 // tha max is MaxProofSize (5134), but in message field it is uint64 594 | if err := binary.Read(r, binary.BigEndian, &proofLen); err != nil { 595 | return err 596 | } 597 | 598 | if proofLen > uint64(secp256k1zkp.MaxProofSize) { 599 | return fmt.Errorf("invalid range proof length: %d", proofLen) 600 | } 601 | 602 | proof := new(bulletproofs.BulletProof) 603 | err := proof.Read(io.LimitReader(r, int64(proofLen))) 604 | if err != nil { 605 | return errors.New("failed to deserialize range proof") 606 | } 607 | o.RangeProof = *proof 608 | 609 | return nil 610 | } 611 | 612 | // Validate returns nil if output successfully passed consensus rules 613 | func (o *Output) Validate() error { 614 | return nil 615 | } 616 | 617 | // String implements String() interface 618 | func (p Output) String() string { 619 | return fmt.Sprintf("%#v", p) 620 | } 621 | 622 | // Hash returns a hash of the serialised output. 623 | func (o *Output) Hash() []byte { 624 | hashed := blake2b.Sum256(o.BytesWithoutProof()) 625 | return hashed[:] 626 | } 627 | 628 | // OutputList sortable list of outputs 629 | type OutputList []Output 630 | 631 | func (m OutputList) Len() int { 632 | return len(m) 633 | } 634 | 635 | // Less is used to order outputs by their hash. 636 | func (m OutputList) Less(i, j int) bool { 637 | return bytes.Compare(m[i].Hash(), m[j].Hash()) < 0 638 | } 639 | 640 | func (m OutputList) Swap(i, j int) { 641 | m[i], m[j] = m[j], m[i] 642 | } 643 | 644 | // SwitchCommitHash the switch commitment hash 645 | type SwitchCommitHash []byte // size = const SwitchCommitHashSize 646 | 647 | // A proof that a transaction sums to zero. Includes both the transaction's 648 | // Pedersen commitment and the signature, that guarantees that the commitments 649 | // amount to zero. 650 | // The signature signs the Fee and the LockHeight, which are retained for 651 | // signature validation. 652 | type TxKernel struct { 653 | // Options for a kernel's structure or use 654 | Features KernelFeatures 655 | // Fee originally included in the transaction this proof is for. 656 | Fee uint64 657 | // This kernel is not valid earlier than lockHeight blocks 658 | // The max lockHeight of all *inputs* to this transaction 659 | LockHeight uint64 660 | // Remainder of the sum of all transaction commitments. If the transaction 661 | // is well formed, amounts components should sum to zero and the excess 662 | // is hence a valid public key. 663 | Excess bulletproofs.Point 664 | // The signature proving the excess is a valid public key, which signs 665 | // the transaction fee. 666 | ExcessSig [64]byte 667 | } 668 | 669 | // Hash returns a hash of the serialised kernel. 670 | func (k *TxKernel) Hash() []byte { 671 | hashed := blake2b.Sum256(k.Bytes()) 672 | return hashed[:] 673 | } 674 | 675 | // Read implements p2p Message interface 676 | func (k *TxKernel) Bytes() []byte { 677 | buff := new(bytes.Buffer) 678 | 679 | // Write features, fee & lock 680 | if err := binary.Write(buff, binary.BigEndian, uint8(k.Features)); err != nil { 681 | logrus.Fatal(err) 682 | } 683 | 684 | if err := binary.Write(buff, binary.BigEndian, k.Fee); err != nil { 685 | logrus.Fatal(err) 686 | } 687 | 688 | if err := binary.Write(buff, binary.BigEndian, k.LockHeight); err != nil { 689 | logrus.Fatal(err) 690 | } 691 | 692 | // Write Excess 693 | if _, err := buff.Write(k.Excess.Bytes()); err != nil { 694 | logrus.Fatal(err) 695 | } 696 | 697 | // Write ExcessSig 698 | if _, err := buff.Write(k.ExcessSig[:]); err != nil { 699 | logrus.Fatal(err) 700 | } 701 | 702 | return buff.Bytes() 703 | } 704 | 705 | // Read implements p2p Message interface 706 | func (k *TxKernel) Read(r io.Reader) error { 707 | // Read features, fee & lock 708 | if err := binary.Read(r, binary.BigEndian, (*uint8)(&k.Features)); err != nil { 709 | return err 710 | } 711 | 712 | if err := binary.Read(r, binary.BigEndian, &k.Fee); err != nil { 713 | return err 714 | } 715 | 716 | if err := binary.Read(r, binary.BigEndian, &k.LockHeight); err != nil { 717 | return err 718 | } 719 | 720 | // Read Excess 721 | if err := k.Excess.Read(r); err != nil { 722 | return err 723 | } 724 | 725 | if _, err := io.ReadFull(r, k.ExcessSig[:]); err != nil { 726 | return err 727 | } 728 | 729 | return nil 730 | } 731 | 732 | var ErrInvalidSignature = errors.New("signature isn't valid") 733 | 734 | // Validate returns nil if kernel successfully passed consensus rules. 735 | func (o *TxKernel) Validate() error { 736 | // The spender signs the fee and lock height using the private key for P. If 737 | // the signature verifies then we know that there is no residue on G (i.e. 738 | // that no value is created) and that the spender is in possession of the 739 | // inputs. 740 | msg := secp256k1zkp.ComputeMessage(o.Fee, o.LockHeight) 741 | signature := secp256k1zkp.DecodeSignature(o.ExcessSig) 742 | 743 | // Excess is a Pedersen commitment to the value zero: P = γ*H + 0*G 744 | P := o.Excess 745 | 746 | if !secp256k1zkp.VerifySignature(P, msg, signature) { 747 | return ErrInvalidSignature 748 | } 749 | 750 | return nil 751 | } 752 | 753 | // String implements String() interface 754 | func (p TxKernel) String() string { 755 | return fmt.Sprintf("%#v", p) 756 | } 757 | 758 | // TxKernelList sortable list of kernels 759 | type TxKernelList []TxKernel 760 | 761 | func (m TxKernelList) Len() int { 762 | return len(m) 763 | } 764 | 765 | // Less is used to order kernels by their hash. 766 | func (m TxKernelList) Less(i, j int) bool { 767 | return bytes.Compare(m[i].Hash(), m[j].Hash()) < 0 768 | } 769 | 770 | func (m TxKernelList) Swap(i, j int) { 771 | m[i], m[j] = m[j], m[i] 772 | } 773 | 774 | // BlockHeader header of the grin-blocks 775 | type BlockHeader struct { 776 | // Version of the block 777 | Version uint16 778 | // Height of this block since the genesis block (height 0) 779 | Height uint64 780 | // Hash of the block previous to this in the chain 781 | Previous Hash 782 | // Root hash of the previous header MMR. 783 | PreviousRoot Hash 784 | // Timestamp at which the block was built 785 | Timestamp time.Time 786 | // UTXORoot Merklish root of all the commitments in the UTXO set 787 | UTXORoot Hash 788 | // RangeProofRoot Merklish root of all range proofs in the UTXO set 789 | RangeProofRoot Hash 790 | // Merklish root of all transaction kernels in the UTXO set 791 | KernelRoot Hash 792 | // Nonce increment used to mine this block 793 | Nonce uint64 794 | // Total accumulated sum of kernel offsets since genesis block. 795 | TotalKernelOffset Hash 796 | // Total accumulated sum of kernel commitments since genesis block. 797 | // Should always equal the UTXO commitment sum minus supply. 798 | TotalKernelSum secp256k1zkp.Commitment 799 | // Total size of the output MMR after applying this block 800 | OutputMmrSize uint64 801 | // Total size of the kernel MMR after applying this block 802 | KernelMmrSize uint64 803 | // Proof of work. 804 | POW Proof 805 | // TODO: Remove or calculate this correctly. 806 | // Difficulty used to mine the block. 807 | Difficulty Difficulty 808 | // Total accumulated difficulty since genesis block 809 | TotalDifficulty Difficulty 810 | // Difficulty scaling factor between the different proofs of work 811 | ScalingDifficulty uint32 812 | } 813 | 814 | // Hash is a hash based on the blocks proof of work. 815 | func (b *BlockHeader) Hash() Hash { 816 | hash := blake2b.Sum256(b.POW.ProofBytes()) 817 | 818 | return hash[:] 819 | } 820 | 821 | // bytesWithoutPOW used in Hash() method, where doesnt need POW data 822 | func (b *BlockHeader) bytesWithoutPOW() []byte { 823 | buff := new(bytes.Buffer) 824 | 825 | // Write version, height of block 826 | if err := binary.Write(buff, binary.BigEndian, b.Version); err != nil { 827 | logrus.Fatal(err) 828 | } 829 | 830 | if err := binary.Write(buff, binary.BigEndian, b.Height); err != nil { 831 | logrus.Fatal(err) 832 | } 833 | 834 | // Write timestamp 835 | if err := binary.Write(buff, binary.BigEndian, b.Timestamp.Unix()); err != nil { 836 | logrus.Fatal(err) 837 | } 838 | 839 | // Write prev blockhash 840 | if len(b.Previous) != BlockHashSize { 841 | logrus.Fatal(errors.New("invalid previous block hash len")) 842 | } 843 | 844 | if _, err := buff.Write(b.Previous); err != nil { 845 | logrus.Fatal(err) 846 | } 847 | 848 | if len(b.PreviousRoot) != BlockHashSize { 849 | logrus.Fatal(errors.New("invalid previous root hash len")) 850 | } 851 | 852 | if _, err := buff.Write(b.PreviousRoot); err != nil { 853 | logrus.Fatal(err) 854 | } 855 | 856 | // Write UTXORoot, RangeProofRoot, KernelRoot 857 | if len(b.UTXORoot) != BlockHashSize || 858 | len(b.RangeProofRoot) != BlockHashSize || 859 | len(b.KernelRoot) != BlockHashSize { 860 | logrus.Fatal(errors.New("invalid UTXORoot/RangeProofRoot/KernelRoot len")) 861 | } 862 | 863 | if _, err := buff.Write(b.UTXORoot); err != nil { 864 | logrus.Fatal(err) 865 | } 866 | 867 | if _, err := buff.Write(b.RangeProofRoot); err != nil { 868 | logrus.Fatal(err) 869 | } 870 | 871 | if _, err := buff.Write(b.KernelRoot); err != nil { 872 | logrus.Fatal(err) 873 | } 874 | 875 | if _, err := buff.Write(b.TotalKernelOffset); err != nil { 876 | logrus.Fatal(err) 877 | } 878 | 879 | if err := binary.Write(buff, binary.BigEndian, b.OutputMmrSize); err != nil { 880 | logrus.Fatal(err) 881 | } 882 | 883 | if err := binary.Write(buff, binary.BigEndian, b.KernelMmrSize); err != nil { 884 | logrus.Fatal(err) 885 | } 886 | 887 | if err := binary.Write(buff, binary.BigEndian, uint64(b.TotalDifficulty)); err != nil { 888 | logrus.Fatal(err) 889 | } 890 | 891 | if err := binary.Write(buff, binary.BigEndian, b.ScalingDifficulty); err != nil { 892 | logrus.Fatal(err) 893 | } 894 | 895 | // Write nonce 896 | if err := binary.Write(buff, binary.BigEndian, b.Nonce); err != nil { 897 | logrus.Fatal(err) 898 | } 899 | 900 | return buff.Bytes() 901 | } 902 | 903 | func (b *BlockHeader) bytesPOW() []byte { 904 | return b.POW.Bytes() 905 | } 906 | 907 | // Bytes implements p2p Message interface 908 | func (b *BlockHeader) Bytes() []byte { 909 | var buff bytes.Buffer 910 | buff.Write(b.bytesWithoutPOW()) 911 | buff.Write(b.bytesPOW()) 912 | 913 | return buff.Bytes() 914 | } 915 | 916 | // Read implements p2p Message interface 917 | func (b *BlockHeader) Read(r io.Reader) error { 918 | // Read version, height of block 919 | if err := binary.Read(r, binary.BigEndian, &b.Version); err != nil { 920 | return err 921 | } 922 | 923 | if err := binary.Read(r, binary.BigEndian, &b.Height); err != nil { 924 | return err 925 | } 926 | 927 | // Read timestamp 928 | var ts int64 929 | if err := binary.Read(r, binary.BigEndian, &ts); err != nil { 930 | return err 931 | } 932 | 933 | // FIXME: Check timestamp is in correct range. 934 | b.Timestamp = time.Unix(ts, 0).UTC() 935 | 936 | // Read prev blockhash 937 | b.Previous = make([]byte, BlockHashSize) 938 | if _, err := io.ReadFull(r, b.Previous); err != nil { 939 | return err 940 | } 941 | 942 | b.PreviousRoot = make([]byte, BlockHashSize) 943 | if _, err := io.ReadFull(r, b.PreviousRoot); err != nil { 944 | return err 945 | } 946 | 947 | // Read UTXORoot, RangeProofRoot, KernelRoot 948 | b.UTXORoot = make([]byte, BlockHashSize) 949 | if _, err := io.ReadFull(r, b.UTXORoot); err != nil { 950 | return err 951 | } 952 | 953 | b.RangeProofRoot = make([]byte, BlockHashSize) 954 | if _, err := io.ReadFull(r, b.RangeProofRoot); err != nil { 955 | return err 956 | } 957 | 958 | b.KernelRoot = make([]byte, BlockHashSize) 959 | if _, err := io.ReadFull(r, b.KernelRoot); err != nil { 960 | return err 961 | } 962 | 963 | b.TotalKernelOffset = make([]byte, secp256k1zkp.SecretKeySize) 964 | if _, err := io.ReadFull(r, b.TotalKernelOffset); err != nil { 965 | return err 966 | } 967 | 968 | if err := binary.Read(r, binary.BigEndian, &b.OutputMmrSize); err != nil { 969 | return err 970 | } 971 | 972 | if err := binary.Read(r, binary.BigEndian, &b.KernelMmrSize); err != nil { 973 | return err 974 | } 975 | 976 | if err := binary.Read(r, binary.BigEndian, &b.TotalDifficulty); err != nil { 977 | return err 978 | } 979 | 980 | if err := binary.Read(r, binary.BigEndian, &b.ScalingDifficulty); err != nil { 981 | return err 982 | } 983 | 984 | if err := binary.Read(r, binary.BigEndian, &b.Nonce); err != nil { 985 | return err 986 | } 987 | 988 | if err := b.POW.Read(r); err != nil { 989 | return err 990 | } 991 | 992 | return nil 993 | } 994 | 995 | // Validate returns nil if header successfully passed consensus rules 996 | func (b *BlockHeader) Validate() error { 997 | logrus.Info("block header validate") 998 | 999 | // Check block header version 1000 | if !ValidateBlockVersion(b.Height, b.Version) { 1001 | return fmt.Errorf("invalid block version %d on height %d, maybe update Gringo?", b.Version, b.Height) 1002 | } 1003 | 1004 | // refuse blocks more than 12 blocks intervals in future (as in bitcoin) 1005 | if b.Timestamp.Sub(time.Now().UTC()) > time.Second*12*BlockTimeSec { 1006 | return fmt.Errorf("invalid block time (%s)", b.Timestamp) 1007 | } 1008 | 1009 | // TODO: Check difficulty. 1010 | 1011 | // Check POW 1012 | isPrimaryPow := b.POW.EdgeBits != SecondPowEdgeBits 1013 | 1014 | // Either the size shift must be a valid primary POW (greater than the 1015 | // minimum size shift) or equal to the secondary POW size shift. 1016 | if b.POW.EdgeBits < DefaultMinEdgeBits && isPrimaryPow { 1017 | return fmt.Errorf("cuckoo size too small: %d", b.POW.EdgeBits) 1018 | } 1019 | 1020 | // The primary POW must have a scaling factor of 1. 1021 | if isPrimaryPow && b.ScalingDifficulty != 1 { 1022 | return fmt.Errorf("invalid scaling difficulty: %d", b.ScalingDifficulty) 1023 | } 1024 | 1025 | if err := b.POW.Validate(b, b.POW.EdgeBits); err != nil { 1026 | return err 1027 | } 1028 | 1029 | return nil 1030 | } 1031 | 1032 | // ValidateBlockVersion helper for validation block header version 1033 | func ValidateBlockVersion(height uint64, version uint16) bool { 1034 | if height < HardForkV2Height { 1035 | return version == 1 1036 | } else if height < HardForkInterval { 1037 | return version == 2 1038 | } else if height < 2*HardForkInterval { 1039 | return version == 3 1040 | } else { 1041 | return false 1042 | } 1043 | } 1044 | 1045 | // String implements String() interface 1046 | func (p BlockHeader) String() string { 1047 | return fmt.Sprintf("%#v", p) 1048 | } 1049 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------