Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

multi: introduce v2transport and implement BIP324 #2260

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions v2transport/chacha.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package v2transport

import (
"crypto/cipher"
"encoding/binary"
"fmt"

"golang.org/x/crypto/chacha20"
"golang.org/x/crypto/chacha20poly1305"
)

const (
// rekeyInterval is the number of messages that can be encrypted or
// decrypted with a single key before we rotate keys.
rekeyInterval = 224

// keySize is the size of the keys used.
keySize = 32
)

// FSChaCha20Poly1305 is a wrapper around ChaCha20Poly1305 that changes its
// nonce after every message and is rekeyed after every rekeying interval.
type FSChaCha20Poly1305 struct {
key []byte
packetCtr uint64
cipher cipher.AEAD
}

// NewFSChaCha20Poly1305 creates a new instance of FSChaCha20Poly1305.
func NewFSChaCha20Poly1305(initialKey []byte) (*FSChaCha20Poly1305, error) {
cipher, err := chacha20poly1305.New(initialKey)
if err != nil {
return nil, err
}

f := &FSChaCha20Poly1305{
key: initialKey,
packetCtr: 0,
cipher: cipher,
}

return f, nil
}

// Encrypt encrypts the plaintext using the associated data, returning the
// ciphertext or an error.
func (f *FSChaCha20Poly1305) Encrypt(aad, plaintext []byte) ([]byte, error) {
return f.crypt(aad, plaintext, false)
}

// Decrypt decrypts the ciphertext using the assosicated data, returning the
// plaintext or an error.
func (f *FSChaCha20Poly1305) Decrypt(aad, ciphertext []byte) ([]byte, error) {
return f.crypt(aad, ciphertext, true)
}

// crypt takes the aad and plaintext/ciphertext and either encrypts or decrypts
// `text` and returns the result. If a failure was encountered, an error will
// be returned.
func (f *FSChaCha20Poly1305) crypt(aad, text []byte,
decrypt bool) ([]byte, error) {

// The nonce is constructed as the 4-byte little-endian encoding of the
// number of messages crypted with the current key followed by the 8-byte
// little-endian encoding of the number of re-keying performed.
var nonce [12]byte
numMsgs := uint32(f.packetCtr % rekeyInterval)
numRekeys := uint64(f.packetCtr / rekeyInterval)
binary.LittleEndian.PutUint32(nonce[0:4], numMsgs)
binary.LittleEndian.PutUint64(nonce[4:12], numRekeys)

var result []byte
if decrypt {
// Decrypt using the nonce, ciphertext, and aad.
var err error
result, err = f.cipher.Open(nil, nonce[:], text, aad)
if err != nil {
// It is ok to error here without incrementing packetCtr because
// we will no longer be decrypting any more messages.
return nil, err
}
} else {
// Encrypt using the nonce, plaintext, and aad.
result = f.cipher.Seal(nil, nonce[:], text, aad)
}

f.packetCtr++

// Rekey if we are at the rekeying interval.
if f.packetCtr%rekeyInterval == 0 {
var rekeyNonce [12]byte
rekeyNonce[0] = 0xff
rekeyNonce[1] = 0xff
rekeyNonce[2] = 0xff
rekeyNonce[3] = 0xff
copy(rekeyNonce[4:], nonce[4:])
var dummyPlaintext [32]byte
f.key = f.cipher.Seal(nil, rekeyNonce[:], dummyPlaintext[:], nil)[:keySize]
cipher, err := chacha20poly1305.New(f.key)
if err != nil {
fmt.Println(err)
return nil, err
}
f.cipher = cipher
}

return result, nil
}

// FSChaCha20 ...
type FSChaCha20 struct {
key []byte
chunkCtr uint64
cipher *chacha20.Cipher
}

// NewFSChaCha20 ...
func NewFSChaCha20(initialKey []byte) (*FSChaCha20, error) {
var initialNonce [12]byte
numRekeys := 0
binary.LittleEndian.PutUint64(initialNonce[4:12], uint64(numRekeys))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/uint64(numRekeys)/0? Since we're not using numRekeys anywhere else.


cipher, err := chacha20.NewUnauthenticatedCipher(
initialKey, initialNonce[:],
)
if err != nil {
return nil, err
}

return &FSChaCha20{
key: initialKey,
chunkCtr: 0,
cipher: cipher,
}, nil
}

// Crypt ...
func (f *FSChaCha20) Crypt(text []byte) ([]byte, error) {
// XOR the text with the keystream to get either the cipher or plaintext.
textLen := len(text)
dst := make([]byte, textLen)
f.cipher.XORKeyStream(dst, text)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we not need th block_counter that's mentioned in the BIP because the standard library handles it all for us? Was a bit confused reading the code for Crypt since it was missing get_keystream_bytes and was wondering if the relevant code isn't needed for us.


// Increment the chunkCtr every time this function is called.
f.chunkCtr++

// Check if we need to rekey.
if f.chunkCtr%rekeyInterval == 0 {
// Get the new key by getting 32 bytes from the keystream. Use all 0's
// so that we can get the actual bytes from XORKeyStream since the
// chacha20 library doesn't supply us with the keystream's bytes
// directly.
var dummyXor [32]byte
var newKey [32]byte
f.cipher.XORKeyStream(newKey[:], dummyXor[:])
f.key = newKey[:]

var nonce [12]byte
numRekeys := f.chunkCtr / rekeyInterval
binary.LittleEndian.PutUint64(nonce[4:12], numRekeys)

cipher, err := chacha20.NewUnauthenticatedCipher(
f.key, nonce[:],
)
if err != nil {
return nil, err
}

f.cipher = cipher
}

return dst, nil
}
17 changes: 17 additions & 0 deletions v2transport/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module v2transport

go 1.23.2

require (
github.com/btcsuite/btcd v0.24.2
github.com/btcsuite/btcd/btcec/v2 v2.3.4
golang.org/x/crypto v0.25.0
)

require (
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
golang.org/x/sys v0.22.0 // indirect
)

replace github.com/btcsuite/btcd/btcec/v2 => ./../btcec
19 changes: 19 additions & 0 deletions v2transport/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
github.com/btcsuite/btcd v0.24.2 h1:aLmxPguqxza+4ag8R1I2nnJjSu2iFn/kqtHTIImswcY=
github.com/btcsuite/btcd v0.24.2/go.mod h1:5C8ChTkl5ejr3WHj8tkQSCmydiMEPB0ZhQhehpq7Dgg=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ=
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading