diff --git a/ec/base58/LICENSE b/ec/base58/LICENSE index 0426ec7..eba799a 100644 --- a/ec/base58/LICENSE +++ b/ec/base58/LICENSE @@ -1,5 +1,5 @@ -Copyright © 2004-2011 by Internet Systems Consortium, Inc. ("ISC") -Copyright © 1995-2003 by Internet Software Consortium +Copyright © 2004-2011 []byte Internet Systems Consortium, Inc. ("ISC") +Copyright © 1995-2003 []byte Internet Software Consortium Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above diff --git a/ec/base58/base58.go b/ec/base58/base58.go index 75cd922..31e4309 100644 --- a/ec/base58/base58.go +++ b/ec/base58/base58.go @@ -27,7 +27,7 @@ var bigRadix = [...]*big.Int{ var bigRadix10 = big.NewInt(58 * 58 * 58 * 58 * 58 * 58 * 58 * 58 * 58 * 58) // 58^10 // Decode decodes a modified base58 string to a byte slice. -func Decode(b st) by { +func Decode(b string) []byte { answer := big.NewInt(0) scratch := new(big.Int) @@ -56,12 +56,12 @@ func Decode(b st) by { total := uint64(0) for _, v := range t[:n] { if v > 255 { - return by("") + return []byte("") } tmp := b58[v] if tmp == 255 { - return by("") + return []byte("") } total = total*58 + uint64(tmp) } @@ -75,27 +75,27 @@ func Decode(b st) by { tmpval := answer.Bytes() - var numZeros no + var numZeros int for numZeros = 0; numZeros < len(b); numZeros++ { if b[numZeros] != alphabetIdx0 { break } } flen := numZeros + len(tmpval) - val := make(by, flen) + val := make([]byte, flen) copy(val[numZeros:], tmpval) return val } // Encode encodes a byte slice to a modified base58 string. -func Encode(b by) st { +func Encode(b []byte) string { x := new(big.Int) x.SetBytes(b) // maximum length of output is log58(2^(8*len(b))) == len(b) * 8 / log(58) - maxlen := no(float64(len(b))*1.365658237309761) + 1 - answer := make(by, 0, maxlen) + maxlen := int(float64(len(b))*1.365658237309761) + 1 + answer := make([]byte, 0, maxlen) mod := new(big.Int) for x.Sign() > 0 { // Calculating with big.Int is slow for each iteration. @@ -138,5 +138,5 @@ func Encode(b by) st { answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i] } - return st(answer) + return string(answer) } diff --git a/ec/base58/base58_test.go b/ec/base58/base58_test.go index 86e490e..8a1c166 100644 --- a/ec/base58/base58_test.go +++ b/ec/base58/base58_test.go @@ -13,8 +13,8 @@ import ( ) var stringTests = []struct { - in st - out st + in string + out string }{ {"", ""}, {" ", "Z"}, @@ -31,8 +31,8 @@ var stringTests = []struct { } var invalidStringTests = []struct { - in st - out st + in string + out string }{ {"0", ""}, {"O", ""}, @@ -49,8 +49,8 @@ var invalidStringTests = []struct { } var hexTests = []struct { - in st - out st + in string + out string }{ {"", ""}, {"61", "2g"}, @@ -75,7 +75,7 @@ var hexTests = []struct { func TestBase58(t *testing.T) { // Encode tests for x, test := range stringTests { - tmp := by(test.in) + tmp := []byte(test.in) if res := base58.Encode(tmp); res != test.out { t.Errorf("Encode test #%d failed: got: %s want: %s", x, res, test.out) @@ -99,7 +99,7 @@ func TestBase58(t *testing.T) { // Decode with invalid input for x, test := range invalidStringTests { - if res := base58.Decode(test.in); st(res) != test.out { + if res := base58.Decode(test.in); string(res) != test.out { t.Errorf("Decode invalidString test #%d failed: got: %q want: %q", x, res, test.out) continue diff --git a/ec/base58/base58bench_test.go b/ec/base58/base58bench_test.go index 673c8e5..a8173a6 100644 --- a/ec/base58/base58bench_test.go +++ b/ec/base58/base58bench_test.go @@ -12,8 +12,8 @@ import ( ) var ( - raw5k = bytes.Repeat(by{0xff}, 5000) - raw100k = bytes.Repeat(by{0xff}, 100*1000) + raw5k = bytes.Repeat([]byte{0xff}, 5000) + raw100k = bytes.Repeat([]byte{0xff}, 100*1000) encoded5k = base58.Encode(raw5k) encoded100k = base58.Encode(raw100k) ) diff --git a/ec/base58/base58check.go b/ec/base58/base58check.go index b33a3a1..2f34ca6 100644 --- a/ec/base58/base58check.go +++ b/ec/base58/base58check.go @@ -18,7 +18,7 @@ var ErrChecksum = errors.New("checksum error") var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing") // checksum: first four bytes of sha256^2 -func checksum(input by) (cksum [4]byte) { +func checksum(input []byte) (cksum [4]byte) { h := sha256.Sum256(input) h2 := sha256.Sum256(h[:]) copy(cksum[:], h2[:4]) @@ -26,8 +26,8 @@ func checksum(input by) (cksum [4]byte) { } // CheckEncode prepends a version byte and appends a four byte checksum. -func CheckEncode(input by, version byte) st { - b := make(by, 0, 1+len(input)+4) +func CheckEncode(input []byte, version byte) string { + b := make([]byte, 0, 1+len(input)+4) b = append(b, version) b = append(b, input...) cksum := checksum(b) @@ -36,7 +36,7 @@ func CheckEncode(input by, version byte) st { } // CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum. -func CheckDecode(input st) (result by, version byte, err er) { +func CheckDecode(input string) (result []byte, version byte, err error) { decoded := Decode(input) if len(decoded) < 5 { return nil, 0, ErrInvalidFormat diff --git a/ec/base58/base58check_test.go b/ec/base58/base58check_test.go index cfca679..dfb84ce 100644 --- a/ec/base58/base58check_test.go +++ b/ec/base58/base58check_test.go @@ -12,8 +12,8 @@ import ( var checkEncodingStringTests = []struct { version byte - in st - out st + in string + out string }{ {20, "", "3MNQE1X"}, {20, " ", "B2Kr6dBE"}, @@ -33,7 +33,7 @@ var checkEncodingStringTests = []struct { func TestBase58Check(t *testing.T) { for x, test := range checkEncodingStringTests { // test encoding - if res := base58.CheckEncode(by(test.in), + if res := base58.CheckEncode([]byte(test.in), test.version); res != test.out { t.Errorf("CheckEncode test #%d failed: got %s, want: %s", x, res, test.out) @@ -49,7 +49,7 @@ func TestBase58Check(t *testing.T) { t.Errorf("CheckDecode test #%d failed: got version: %d want: %d", x, version, test.version) - case st(res) != test.in: + case string(res) != test.in: t.Errorf("CheckDecode test #%d failed: got: %s want: %s", x, res, test.in) } diff --git a/ec/base58/example_test.go b/ec/base58/example_test.go index be6a333..e3c161e 100644 --- a/ec/base58/example_test.go +++ b/ec/base58/example_test.go @@ -17,7 +17,7 @@ func ExampleDecode() { decoded := base58.Decode(encoded) // Show the decoded data. - fmt.Println("Decoded Data:", st(decoded)) + fmt.Println("Decoded Data:", string(decoded)) // Output: // Decoded Data: Test data @@ -27,7 +27,7 @@ func ExampleDecode() { // encoding scheme. func ExampleEncode() { // Encode example data with the modified base58 encoding scheme. - data := by("Test data") + data := []byte("Test data") encoded := base58.Encode(data) // Show the encoded data. @@ -60,7 +60,7 @@ func ExampleCheckDecode() { // scheme. func ExampleCheckEncode() { // Encode example data with the Base58Check encoding scheme. - data := by("Test data") + data := []byte("Test data") encoded := base58.CheckEncode(data, 0) // Show the encoded data. diff --git a/ec/base58/genalphabet.go b/ec/base58/genalphabet.go index da63cbf..9cb8702 100644 --- a/ec/base58/genalphabet.go +++ b/ec/base58/genalphabet.go @@ -16,7 +16,7 @@ import ( ) var ( - start = by(`// Copyright (c) 2015 The btcsuite developers + start = []byte(`// Copyright (c) 2015 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. @@ -33,17 +33,17 @@ const ( var b58 = [256]byte{`) - end = by(`}`) + end = []byte(`}`) - alphabet = by("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") - tab = by("\t") - invalid = by("255") - comma = by(",") - space = by(" ") - nl = by("\n") + alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + tab = []byte("\t") + invalid = []byte("255") + comma = []byte(",") + space = []byte(" ") + nl = []byte("\n") ) -func write(w io.Writer, b by) { +func write(w io.Writer, b []byte) { _, err := w.Write(b) if err != nil { log.Fatal(err) diff --git a/ec/base58/util.go b/ec/base58/util.go index a79b97d..1aa0ec4 100644 --- a/ec/base58/util.go +++ b/ec/base58/util.go @@ -1,22 +1,9 @@ package base58 import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/base58/util_test.go b/ec/base58/util_test.go index 731b7a4..9b58c16 100644 --- a/ec/base58/util_test.go +++ b/ec/base58/util_test.go @@ -1,22 +1,9 @@ package base58_test import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/bech32/bech32.go b/ec/bech32/bech32.go index 32f42f3..c27003b 100644 --- a/ec/bech32/bech32.go +++ b/ec/bech32/bech32.go @@ -18,12 +18,12 @@ import ( const Charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" // gen encodes the generator polynomial for the bech32 BCH checksum. -var gen = []no{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} +var gen = []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} // toBytes converts each character in the string 'chars' to the value of the // index of the corresponding character in 'charset'. -func toBytes(chars by) (by, er) { - decoded := make(by, 0, len(chars)) +func toBytes(chars []byte) ([]byte, error) { + decoded := make([]byte, 0, len(chars)) for i := 0; i < len(chars); i++ { index := strings.IndexByte(Charset, chars[i]) if index < 0 { @@ -41,12 +41,12 @@ func toBytes(chars by) (by, er) { // 32), otherwise the results are undefined. // // For more details on the polymod calculation, please refer to BIP 173. -func bech32Polymod(hrp by, values, checksum by) no { +func bech32Polymod(hrp []byte, values, checksum []byte) int { check := 1 // Account for the high bits of the HRP in the checksum. for i := 0; i < len(hrp); i++ { b := check >> 25 - hiBits := no(hrp[i]) >> 5 + hiBits := int(hrp[i]) >> 5 check = (check&0x1ffffff)<<5 ^ hiBits for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { @@ -66,7 +66,7 @@ func bech32Polymod(hrp by, values, checksum by) no { // Account for the low bits of the HRP. for i := 0; i < len(hrp); i++ { b := check >> 25 - loBits := no(hrp[i]) & 31 + loBits := int(hrp[i]) & 31 check = (check&0x1ffffff)<<5 ^ loBits for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { @@ -77,7 +77,7 @@ func bech32Polymod(hrp by, values, checksum by) no { // Account for the values. for _, v := range values { b := check >> 25 - check = (check&0x1ffffff)<<5 ^ no(v) + check = (check&0x1ffffff)<<5 ^ int(v) for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { check ^= gen[i] @@ -100,7 +100,7 @@ func bech32Polymod(hrp by, values, checksum by) no { // Checksum is provided during decoding, so use it. for _, v := range checksum { b := check >> 25 - check = (check&0x1ffffff)<<5 ^ no(v) + check = (check&0x1ffffff)<<5 ^ int(v) for i := 0; i < 5; i++ { if (b>>uint(i))&1 == 1 { check ^= gen[i] @@ -120,10 +120,10 @@ func bech32Polymod(hrp by, values, checksum by) no { // and 126), otherwise the results are undefined. // // For more details on the checksum calculation, please refer to BIP 173. -func writeBech32Checksum(hrp by, data by, bldr *bytes.Buffer, +func writeBech32Checksum(hrp []byte, data []byte, bldr *bytes.Buffer, version Version) { - bech32Const := no(VersionToConsts[version]) + bech32Const := int(VersionToConsts[version]) polymod := bech32Polymod(hrp, data, nil) ^ bech32Const for i := 0; i < 6; i++ { b := byte((polymod >> uint(5*(5-i))) & 31) @@ -143,7 +143,7 @@ func writeBech32Checksum(hrp by, data by, bldr *bytes.Buffer, // Data MUST have more than 6 elements, otherwise this function panics. // // For more details on the checksum verification, please refer to BIP 173. -func bech32VerifyChecksum(hrp by, data by) (Version, bo) { +func bech32VerifyChecksum(hrp []byte, data []byte) (Version, bool) { checksum := data[len(data)-6:] values := data[:len(data)-6] polymod := bech32Polymod(hrp, values, checksum) @@ -163,14 +163,14 @@ func bech32VerifyChecksum(hrp by, data by) (Version, bo) { // decoder. This function will return the version of the decoded checksum // constant so higher level validation can be performed to ensure the correct // version of bech32 was used when encoding. -func decodeNoLimit(bech by) (by, by, Version, er) { +func decodeNoLimit(bech []byte) ([]byte, []byte, Version, error) { // The minimum allowed size of a bech32 string is 8 characters, since it // needs a non-empty HRP, a separator, and a 6 character checksum. if len(bech) < 8 { return nil, nil, VersionUnknown, ErrInvalidLength(len(bech)) } // Only ASCII characters between 33 and 126 are allowed. - var hasLower, hasUpper bo + var hasLower, hasUpper bool for i := 0; i < len(bech); i++ { if bech[i] < 33 || bech[i] > 126 { return nil, nil, VersionUnknown, ErrInvalidCharacter(bech[i]) @@ -228,7 +228,7 @@ func decodeNoLimit(bech by) (by, by, Version, er) { err = ErrInvalidChecksum{ Expected: expectedVersion0, ExpectedM: expectedVersionM, - Actual: st(actual), + Actual: string(actual), } return nil, nil, VersionUnknown, err } @@ -244,7 +244,7 @@ func decodeNoLimit(bech by) (by, by, Version, er) { // // Note that the returned data is 5-bit (base32) encoded and the human-readable // part will be lowercase. -func DecodeNoLimit(bech by) (by, by, er) { +func DecodeNoLimit(bech []byte) ([]byte, []byte, error) { hrp, data, _, err := decodeNoLimit(bech) return hrp, data, err } @@ -254,7 +254,7 @@ func DecodeNoLimit(bech by) (by, by, er) { // // Note that the returned data is 5-bit (base32) encoded and the human-readable // part will be lowercase. -func Decode(bech by) (by, by, er) { +func Decode(bech []byte) ([]byte, []byte, error) { // The maximum allowed length for a bech32 string is 90. if len(bech) > 90 { return nil, nil, ErrInvalidLength(len(bech)) @@ -267,7 +267,7 @@ func Decode(bech by) (by, by, er) { // return bech32 version that matches the decoded checksum. This method should // be used when decoding segwit addresses, as it enables additional // verification to ensure the proper checksum is used. -func DecodeGeneric(bech by) (by, by, Version, er) { +func DecodeGeneric(bech []byte) ([]byte, []byte, Version, error) { // The maximum allowed length for a bech32 string is 90. if len(bech) > 90 { return nil, nil, VersionUnknown, ErrInvalidLength(len(bech)) @@ -278,7 +278,7 @@ func DecodeGeneric(bech by) (by, by, Version, er) { // encodeGeneric is the base bech32 encoding function that is aware of the // existence of the checksum versions. This method is private, as the Encode // and EncodeM methods are intended to be used instead. -func encodeGeneric(hrp by, data by, version Version) (by, er) { +func encodeGeneric(hrp []byte, data []byte, version Version) ([]byte, error) { // The resulting bech32 string is the concatenation of the lowercase // hrp, the separator 1, data and the 6-byte checksum. hrp = bytes.ToLower(hrp) @@ -288,7 +288,7 @@ func encodeGeneric(hrp by, data by, version Version) (by, er) { bldr.WriteString("1") // Write the data part, using the bech32 charset. for _, b := range data { - if no(b) >= len(Charset) { + if int(b) >= len(Charset) { return nil, ErrInvalidDataByte(b) } bldr.WriteByte(Charset[b]) @@ -302,21 +302,21 @@ func encodeGeneric(hrp by, data by, version Version) (by, er) { // human-readable part (HRP). The HRP will be converted to lowercase if needed // since mixed cased encodings are not permitted and lowercase is used for // checksum purposes. Note that the bytes must each encode 5 bits (base32). -func Encode(hrp, data by) (by, er) { +func Encode(hrp, data []byte) ([]byte, error) { return encodeGeneric(hrp, data, Version0) } // EncodeM is the exactly same as the Encode method, but it uses the new // bech32m constant instead of the original one. It should be used whenever one // attempts to encode a segwit address of v1 and beyond. -func EncodeM(hrp, data by) (by, er) { +func EncodeM(hrp, data []byte) ([]byte, error) { return encodeGeneric(hrp, data, VersionM) } // ConvertBits converts a byte slice where each byte is encoding fromBits bits, // to a byte slice where each byte is encoding toBits bits. -func ConvertBits(data by, fromBits, toBits uint8, pad bo) (by, - er) { +func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, + error) { if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 { return nil, ErrInvalidBitGroups{} @@ -326,9 +326,9 @@ func ConvertBits(data by, fromBits, toBits uint8, pad bo) (by, // by a byte depending on whether padding is used or not and if the input // data is a multiple of both fromBits and toBits, but we ignore that and // just size it to the maximum possible. - maxSize := len(data)*no(fromBits)/no(toBits) + 1 + maxSize := len(data)*int(fromBits)/int(toBits) + 1 // The final bytes, each byte encoding toBits bits. - regrouped := make(by, 0, maxSize) + regrouped := make([]byte, 0, maxSize) // Keep track of the next byte we create and how many bits we have // added to it out of the toBits goal. nextByte := byte(0) @@ -383,7 +383,7 @@ func ConvertBits(data by, fromBits, toBits uint8, pad bo) (by, // human-readable part (HRP). The HRP will be converted to lowercase if needed // since mixed cased encodings are not permitted and lowercase is used for // checksum purposes. -func EncodeFromBase256(hrp, data by) (by, er) { +func EncodeFromBase256(hrp, data []byte) ([]byte, error) { converted, err := ConvertBits(data, 8, 5, true) if err != nil { return nil, err @@ -394,7 +394,7 @@ func EncodeFromBase256(hrp, data by) (by, er) { // DecodeToBase256 decodes a bech32-encoded string into its associated // human-readable part (HRP) and base32-encoded data, converts that data to a // base256-encoded byte slice and returns it along with the lowercase HRP. -func DecodeToBase256(bech by) (by, by, er) { +func DecodeToBase256(bech []byte) ([]byte, []byte, error) { hrp, data, err := Decode(bech) if err != nil { return nil, nil, err diff --git a/ec/bech32/bech32_test.go b/ec/bech32/bech32_test.go index c574cdb..dce7dbf 100644 --- a/ec/bech32/bech32_test.go +++ b/ec/bech32/bech32_test.go @@ -19,8 +19,8 @@ import ( // reason. func TestBech32(t *testing.T) { tests := []struct { - str st - expectedError er + str string + expectedError error }{ {"A12UEL5L", nil}, {"a12uel5l", nil}, @@ -62,8 +62,8 @@ func TestBech32(t *testing.T) { {"A12uEL5L", ErrMixedCase{}}, } for i, test := range tests { - str := by(test.str) - hrp, decoded, err := Decode(by(str)) + str := []byte(test.str) + hrp, decoded, err := Decode([]byte(str)) if !errors.Is(err, test.expectedError) { t.Errorf("%d: expected decoding error %v "+ "instead got %v", i, test.expectedError, err) @@ -78,13 +78,13 @@ func TestBech32(t *testing.T) { if err != nil { t.Errorf("encoding failed: %v", err) } - if !equals(encoded, bytes.ToLower(by(str))) { + if !bytes.Equal(encoded, bytes.ToLower([]byte(str))) { t.Errorf("expected data to encode to %v, but got %v", str, encoded) } // Flip a bit in the string an make sure it is caught. pos := bytes.LastIndexAny(str, "1") - flipped := by(st(str[:pos+1]) + st(str[pos+1]^1) + st(str[pos+2:])) + flipped := []byte(string(str[:pos+1]) + string(str[pos+1]^1) + string(str[pos+2:])) _, _, err = Decode(flipped) if err == nil { t.Error("expected decoding to fail") @@ -98,8 +98,8 @@ func TestBech32(t *testing.T) { // vectors, but end up with different checksums. func TestBech32M(t *testing.T) { tests := []struct { - str st - expectedError er + str string + expectedError error }{ {"A1LQFN3A", nil}, {"a1lqfn3a", nil}, @@ -132,7 +132,7 @@ func TestBech32M(t *testing.T) { {"\x801eym55h", ErrInvalidCharacter(0x80)}, } for i, test := range tests { - str := by(test.str) + str := []byte(test.str) hrp, decoded, err := Decode(str) if test.expectedError != err { t.Errorf("%d: (%v) expected decoding error %v "+ @@ -150,13 +150,13 @@ func TestBech32M(t *testing.T) { t.Errorf("encoding failed: %v", err) } - if !equals(encoded, bytes.ToLower(str)) { + if !bytes.Equal(encoded, bytes.ToLower(str)) { t.Errorf("expected data to encode to %v, but got %v", str, encoded) } // Flip a bit in the string an make sure it is caught. pos := bytes.LastIndexAny(str, "1") - flipped := by(st(str[:pos+1]) + st(str[pos+1]^1) + st(str[pos+2:])) + flipped := []byte(string(str[:pos+1]) + string(str[pos+1]^1) + string(str[pos+2:])) _, _, err = Decode(flipped) if err == nil { t.Error("expected decoding to fail") @@ -169,7 +169,7 @@ func TestBech32M(t *testing.T) { // segwit addr validation. func TestBech32DecodeGeneric(t *testing.T) { tests := []struct { - str st + str string version Version }{ {"A1LQFN3A", VersionM}, @@ -206,7 +206,7 @@ func TestBech32DecodeGeneric(t *testing.T) { VersionM}, } for i, test := range tests { - _, _, version, err := DecodeGeneric(by(test.str)) + _, _, version, err := DecodeGeneric([]byte(test.str)) if err != nil { t.Errorf("%d: (%v) unexpected error during "+ "decoding: %v", i, test.str, err) @@ -224,10 +224,10 @@ func TestBech32DecodeGeneric(t *testing.T) { // to all uppercase produces the lowercase HRP and original data. func TestMixedCaseEncode(t *testing.T) { tests := []struct { - name st - hrp st - data st - encoded st + name string + hrp string + data string + encoded string }{{ name: "all uppercase HRP with no data", hrp: "A", @@ -269,25 +269,25 @@ func TestMixedCaseEncode(t *testing.T) { err) continue } - gotEncoded, err := Encode(by(test.hrp), convertedData) + gotEncoded, err := Encode([]byte(test.hrp), convertedData) if err != nil { t.Errorf("%q: unexpected encode error: %v", test.name, err) continue } - if !equals(gotEncoded, by(test.encoded)) { + if !bytes.Equal(gotEncoded, []byte(test.encoded)) { t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, gotEncoded, test.encoded) continue } // Ensure the decoding the expected lowercase encoding converted to all // uppercase produces the lowercase HRP and original data. - gotHRP, gotData, err := Decode(bytes.ToUpper(by(test.encoded))) + gotHRP, gotData, err := Decode(bytes.ToUpper([]byte(test.encoded))) if err != nil { t.Errorf("%q: unexpected decode error: %v", test.name, err) continue } wantHRP := strings.ToLower(test.hrp) - if !equals(gotHRP, by(wantHRP)) { + if !bytes.Equal(gotHRP, []byte(wantHRP)) { t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", test.name, gotHRP, wantHRP) continue @@ -298,7 +298,7 @@ func TestMixedCaseEncode(t *testing.T) { err) continue } - if !equals(convertedGotData, data) { + if !bytes.Equal(convertedGotData, data) { t.Errorf("%q: mismatched data -- got %x, want %x", test.name, convertedGotData, data) continue @@ -311,18 +311,18 @@ func TestMixedCaseEncode(t *testing.T) { func TestCanDecodeUnlimtedBech32(t *testing.T) { input := "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq5kx0yd" // Sanity check that an input of this length errors on regular Decode() - _, _, err := Decode(by(input)) + _, _, err := Decode([]byte(input)) if err == nil { t.Fatalf("Test vector not appropriate") } // Try and decode it. - hrp, data, err := DecodeNoLimit(by(input)) + hrp, data, err := DecodeNoLimit([]byte(input)) if err != nil { t.Fatalf("Expected decoding of large string to work. Got error: %v", err) } // Verify data for correctness. - if !equals(hrp, by("1")) { + if !bytes.Equal(hrp, []byte("1")) { t.Fatalf("Unexpected hrp: %v", hrp) } decodedHex := fmt.Sprintf("%x", data) @@ -338,11 +338,11 @@ func TestCanDecodeUnlimtedBech32(t *testing.T) { // manipulations. func TestBech32Base256(t *testing.T) { tests := []struct { - name st // test name - encoded st // bech32 string to decode - hrp st // expected human-readable part - data st // expected hex-encoded data - err er // expected error + name string // test name + encoded string // bech32 string to decode + hrp string // expected human-readable part + data string // expected hex-encoded data + err error // expected error }{{ name: "all uppercase, no data", encoded: "A12UEL5L", @@ -412,7 +412,7 @@ func TestBech32Base256(t *testing.T) { for _, test := range tests { // Ensure the decode either produces an error or not as expected. str := test.encoded - gotHRP, gotData, err := DecodeToBase256(by(str)) + gotHRP, gotData, err := DecodeToBase256([]byte(str)) if test.err != err { t.Errorf("%q: unexpected decode error -- got %v, want %v", test.name, err, test.err) @@ -423,7 +423,7 @@ func TestBech32Base256(t *testing.T) { continue } // Ensure the expected HRP and original data are as expected. - if !equals(gotHRP, by(test.hrp)) { + if !bytes.Equal(gotHRP, []byte(test.hrp)) { t.Errorf("%q: mismatched decoded HRP -- got %q, want %q", test.name, gotHRP, test.hrp) continue @@ -433,7 +433,7 @@ func TestBech32Base256(t *testing.T) { t.Errorf("%q: invalid hex %q: %v", test.name, test.data, err) continue } - if !equals(gotData, data) { + if !bytes.Equal(gotData, data) { t.Errorf("%q: mismatched data -- got %x, want %x", test.name, gotData, data) continue @@ -441,25 +441,25 @@ func TestBech32Base256(t *testing.T) { // Encode the same data with the HRP converted to all uppercase and // ensure the result is the lowercase version of the original encoded // bech32 string. - gotEncoded, err := EncodeFromBase256(bytes.ToUpper(by(test.hrp)), data) + gotEncoded, err := EncodeFromBase256(bytes.ToUpper([]byte(test.hrp)), data) if err != nil { t.Errorf("%q: unexpected uppercase HRP encode error: %v", test.name, err) } - wantEncoded := bytes.ToLower(by(str)) - if !equals(gotEncoded, wantEncoded) { + wantEncoded := bytes.ToLower([]byte(str)) + if !bytes.Equal(gotEncoded, wantEncoded) { t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, gotEncoded, wantEncoded) } // Encode the same data with the HRP converted to all lowercase and // ensure the result is the lowercase version of the original encoded // bech32 string. - gotEncoded, err = EncodeFromBase256(bytes.ToLower(by(test.hrp)), data) + gotEncoded, err = EncodeFromBase256(bytes.ToLower([]byte(test.hrp)), data) if err != nil { t.Errorf("%q: unexpected lowercase HRP encode error: %v", test.name, err) } - if !equals(gotEncoded, wantEncoded) { + if !bytes.Equal(gotEncoded, wantEncoded) { t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, gotEncoded, wantEncoded) } @@ -469,7 +469,7 @@ func TestBech32Base256(t *testing.T) { var mixedHRPBuilder bytes.Buffer for i, r := range test.hrp { if i%2 == 0 { - mixedHRPBuilder.WriteString(strings.ToUpper(st(r))) + mixedHRPBuilder.WriteString(strings.ToUpper(string(r))) continue } mixedHRPBuilder.WriteRune(r) @@ -479,14 +479,14 @@ func TestBech32Base256(t *testing.T) { t.Errorf("%q: unexpected lowercase HRP encode error: %v", test.name, err) } - if !equals(gotEncoded, wantEncoded) { + if !bytes.Equal(gotEncoded, wantEncoded) { t.Errorf("%q: mismatched encoding -- got %q, want %q", test.name, gotEncoded, wantEncoded) } // Ensure a bit flip in the string is caught. pos := strings.LastIndexAny(test.encoded, "1") - flipped := str[:pos+1] + st(str[pos+1]^1) + str[pos+2:] - _, _, err = DecodeToBase256(by(flipped)) + flipped := str[:pos+1] + string(str[pos+1]^1) + str[pos+2:] + _, _, err = DecodeToBase256([]byte(flipped)) if err == nil { t.Error("expected decoding to fail") } @@ -516,7 +516,7 @@ func BenchmarkEncodeDecodeCycle(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - str, err := Encode(by(hrp), base32Input) + str, err := Encode([]byte(hrp), base32Input) if err != nil { b.Fatalf("failed to encode input: %v", err) } @@ -530,11 +530,11 @@ func BenchmarkEncodeDecodeCycle(b *testing.B) { // TestConvertBits tests whether base conversion works using TestConvertBits(). func TestConvertBits(t *testing.T) { tests := []struct { - input st - output st + input string + output string fromBits uint8 toBits uint8 - pad bo + pad bool }{ // Trivial empty conversions. {"", "", 8, 5, false}, @@ -590,7 +590,7 @@ func TestConvertBits(t *testing.T) { if err != nil { t.Fatalf("test case %d failed: %v", i, err) } - if !equals(actual, expected) { + if !bytes.Equal(actual, expected) { t.Fatalf("test case %d has wrong output; expected=%x actual=%x", i, expected, actual) } @@ -601,11 +601,11 @@ func TestConvertBits(t *testing.T) { // ConvertBits(). func TestConvertBitsFailures(t *testing.T) { tests := []struct { - input st + input string fromBits uint8 toBits uint8 - pad bo - err er + pad bool + err error }{ // Not enough output bytes when not using padding. {"ff", 8, 5, false, ErrInvalidIncompleteGroup{}}, diff --git a/ec/bech32/error.go b/ec/bech32/error.go index 0152906..7a6b86d 100644 --- a/ec/bech32/error.go +++ b/ec/bech32/error.go @@ -12,7 +12,7 @@ import ( // characters. type ErrMixedCase struct{} -func (err ErrMixedCase) Error() st { +func (err ErrMixedCase) Error() string { return "string not all lowercase or all uppercase" } @@ -20,7 +20,7 @@ func (err ErrMixedCase) Error() st { // slices using bit-per-element of unsupported value. type ErrInvalidBitGroups struct{} -func (err ErrInvalidBitGroups) Error() st { +func (err ErrInvalidBitGroups) Error() string { return "only bit groups between 1 and 8 allowed" } @@ -28,52 +28,52 @@ func (err ErrInvalidBitGroups) Error() st { // data of wrong length. type ErrInvalidIncompleteGroup struct{} -func (err ErrInvalidIncompleteGroup) Error() st { +func (err ErrInvalidIncompleteGroup) Error() string { return "invalid incomplete group" } // ErrInvalidLength is returned when the bech32 string has an invalid length // given the BIP-173 defined restrictions. -type ErrInvalidLength no +type ErrInvalidLength int -func (err ErrInvalidLength) Error() st { - return fmt.Sprintf("invalid bech32 string length %d", no(err)) +func (err ErrInvalidLength) Error() string { + return fmt.Sprintf("invalid bech32 string length %d", int(err)) } // ErrInvalidCharacter is returned when the bech32 string has a character // outside the range of the supported charset. type ErrInvalidCharacter rune -func (err ErrInvalidCharacter) Error() st { +func (err ErrInvalidCharacter) Error() string { return fmt.Sprintf("invalid character in string: '%c'", rune(err)) } // ErrInvalidSeparatorIndex is returned when the separator character '1' is // in an invalid position in the bech32 string. -type ErrInvalidSeparatorIndex no +type ErrInvalidSeparatorIndex int -func (err ErrInvalidSeparatorIndex) Error() st { - return fmt.Sprintf("invalid separator index %d", no(err)) +func (err ErrInvalidSeparatorIndex) Error() string { + return fmt.Sprintf("invalid separator index %d", int(err)) } // ErrNonCharsetChar is returned when a character outside of the specific // bech32 charset is used in the string. type ErrNonCharsetChar rune -func (err ErrNonCharsetChar) Error() st { - return fmt.Sprintf("invalid character not part of charset: %v", no(err)) +func (err ErrNonCharsetChar) Error() string { + return fmt.Sprintf("invalid character not part of charset: %v", int(err)) } // ErrInvalidChecksum is returned when the extracted checksum of the string // is different than what was expected. Both the original version, as well as // the new bech32m checksum may be specified. type ErrInvalidChecksum struct { - Expected st - ExpectedM st - Actual st + Expected string + ExpectedM string + Actual string } -func (err ErrInvalidChecksum) Error() st { +func (err ErrInvalidChecksum) Error() string { return fmt.Sprintf("invalid checksum (expected (bech32=%v, "+ "bech32m=%v), got %v)", err.Expected, err.ExpectedM, err.Actual) } @@ -82,6 +82,6 @@ func (err ErrInvalidChecksum) Error() st { // conversion into a string was found. type ErrInvalidDataByte byte -func (err ErrInvalidDataByte) Error() st { +func (err ErrInvalidDataByte) Error() string { return fmt.Sprintf("invalid data byte: %v", byte(err)) } diff --git a/ec/bech32/example_test.go b/ec/bech32/example_test.go index 59c63ca..ae15651 100644 --- a/ec/bech32/example_test.go +++ b/ec/bech32/example_test.go @@ -12,7 +12,7 @@ import ( // This example demonstrates how to decode a bech32 encoded string. func ExampleDecode() { encoded := "bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx" - hrp, decoded, err := Decode(by(encoded)) + hrp, decoded, err := Decode([]byte(encoded)) if err != nil { fmt.Println("Error:", err) } @@ -26,13 +26,13 @@ func ExampleDecode() { // This example demonstrates how to encode data into a bech32 string. func ExampleEncode() { - data := by("Test data") + data := []byte("Test data") // Convert test data to base32: conv, err := ConvertBits(data, 8, 5, true) if err != nil { fmt.Println("Error:", err) } - encoded, err := Encode(by("customHrp!11111q"), conv) + encoded, err := Encode([]byte("customHrp!11111q"), conv) if err != nil { fmt.Println("Error:", err) } diff --git a/ec/bech32/util.go b/ec/bech32/util.go index d925d8f..66a3b8a 100644 --- a/ec/bech32/util.go +++ b/ec/bech32/util.go @@ -1,22 +1,9 @@ package bech32 import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/bech32/version.go b/ec/bech32/version.go index 7b1a914..c1e75d2 100644 --- a/ec/bech32/version.go +++ b/ec/bech32/version.go @@ -2,7 +2,7 @@ package bech32 // ChecksumConst is a type that represents the currently defined bech32 // checksum constants. -type ChecksumConst no +type ChecksumConst int const ( // Version0Const is the original constant used in the checksum diff --git a/ec/bench_test.go b/ec/bench_test.go index 865b7b5..9d36959 100644 --- a/ec/bench_test.go +++ b/ec/bench_test.go @@ -19,7 +19,7 @@ import ( // // The field value is returned to support chaining. This enables syntax like: // f := new(FieldVal).SetHex("0abc").Add(1) so that f = 0x0abc + 1 -func setHex(hexString st) *FieldVal { +func setHex(hexString string) *FieldVal { if len(hexString)%2 != 0 { hexString = "0" + hexString } @@ -33,7 +33,7 @@ func setHex(hexString st) *FieldVal { // if there is an error. This is only provided for the hard-coded constants so // errors in the source code can be detected. It will only (and must only) be // called with hard-coded values. -func hexToFieldVal(s st) *FieldVal { +func hexToFieldVal(s string) *FieldVal { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -49,7 +49,7 @@ func hexToFieldVal(s st) *FieldVal { // panic is there is an error. This is only provided for the hard-coded // constants so errors in the source code can bet detected. It will only (and // must only) be called for initialization purposes. -func fromHex(s st) *big.Int { +func fromHex(s string) *big.Int { if s == "" { return big.NewInt(0) } @@ -63,7 +63,7 @@ func fromHex(s st) *big.Int { // jacobianPointFromHex decodes the passed big-endian hex strings into a // Jacobian point with its internal fields set to the resulting values. Only // the first 32-bytes are used. -func jacobianPointFromHex(x, y, z st) JacobianPoint { +func jacobianPointFromHex(x, y, z string) JacobianPoint { var p JacobianPoint p.X = *setHex(x) p.Y = *setHex(y) @@ -147,7 +147,7 @@ func BenchmarkScalarMult(b *testing.B) { // panic if there is an error. This is only provided for the hard-coded // constants so errors in the source code can be detected. It will only (and // must only) be called with hard-coded values. -func hexToModNScalar(s st) *ModNScalar { +func hexToModNScalar(s string) *ModNScalar { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -176,7 +176,7 @@ func BenchmarkParseCompressedPubKey(b *testing.B) { var ( pk *PublicKey - err er + err error ) b.ReportAllocs() b.ResetTimer() diff --git a/ec/btcec_test.go b/ec/btcec_test.go index 4b8260f..3d80d79 100644 --- a/ec/btcec_test.go +++ b/ec/btcec_test.go @@ -15,7 +15,7 @@ import ( // isJacobianOnS256Curve returns boolean if the point (x,y,z) is on the // secp256k1 curve. -func isJacobianOnS256Curve(point *JacobianPoint) bo { +func isJacobianOnS256Curve(point *JacobianPoint) bool { // Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7 // In Jacobian coordinates, Y = y/z^3 and X = x/z^2 // Thus: @@ -33,9 +33,9 @@ func isJacobianOnS256Curve(point *JacobianPoint) bo { // TestAddJacobian tests addition of points projected in Jacobian coordinates. func TestAddJacobian(t *testing.T) { tests := []struct { - x1, y1, z1 st // Coordinates (in hex) of first point to add - x2, y2, z2 st // Coordinates (in hex) of second point to add - x3, y3, z3 st // Coordinates (in hex) of expected point + x1, y1, z1 string // Coordinates (in hex) of first point to add + x2, y2, z2 string // Coordinates (in hex) of second point to add + x3, y3, z3 string // Coordinates (in hex) of expected point }{ // Addition with a point at infinity (left hand side). // ∞ + P = P @@ -259,9 +259,9 @@ func TestAddJacobian(t *testing.T) { // TestAddAffine tests addition of points in affine coordinates. func TestAddAffine(t *testing.T) { tests := []struct { - x1, y1 st // Coordinates (in hex) of first point to add - x2, y2 st // Coordinates (in hex) of second point to add - x3, y3 st // Coordinates (in hex) of expected point + x1, y1 string // Coordinates (in hex) of first point to add + x2, y2 string // Coordinates (in hex) of second point to add + x3, y3 string // Coordinates (in hex) of expected point }{ // Addition with a point at infinity (left hand side). // ∞ + P = P @@ -354,7 +354,7 @@ func TestAddAffine(t *testing.T) { // equal in affine coordinates, while not having the same coordinates in // projective space, so the two points not being equal doesn't necessarily mean // they aren't actually the same affine point. -func isStrictlyEqual(p, other *JacobianPoint) bo { +func isStrictlyEqual(p, other *JacobianPoint) bool { return p.X.Equals(&other.X) && p.Y.Equals(&other.Y) && p.Z.Equals(&other.Z) } @@ -362,8 +362,8 @@ func isStrictlyEqual(p, other *JacobianPoint) bo { // coordinates. func TestDoubleJacobian(t *testing.T) { tests := []struct { - x1, y1, z1 st // Coordinates (in hex) of point to double - x3, y3, z3 st // Coordinates (in hex) of expected point + x1, y1, z1 string // Coordinates (in hex) of point to double + x3, y3, z3 string // Coordinates (in hex) of expected point }{ // Doubling a point at infinity is still infinity. { @@ -435,8 +435,8 @@ func TestDoubleJacobian(t *testing.T) { // TestDoubleAffine tests doubling of points in affine coordinates. func TestDoubleAffine(t *testing.T) { tests := []struct { - x1, y1 st // Coordinates (in hex) of point to double - x3, y3 st // Coordinates (in hex) of expected point + x1, y1 string // Coordinates (in hex) of point to double + x3, y3 string // Coordinates (in hex) of expected point }{ // Doubling a point at infinity is still infinity. // 2*∞ = ∞ (point at infinity) @@ -510,8 +510,8 @@ func TestOnCurve(t *testing.T) { } type baseMultTest struct { - k st - x, y st + k string + x, y string } // TODO: add more test vectors @@ -566,7 +566,7 @@ func TestBaseMultVerify(t *testing.T) { s256 := S256() for bytes := 1; bytes < 40; bytes++ { for i := 0; i < 30; i++ { - data := make(by, bytes) + data := make([]byte, bytes) _, err := rand.Read(data) if err != nil { t.Errorf("failed to read random data for %d", i) @@ -587,11 +587,11 @@ func TestBaseMultVerify(t *testing.T) { func TestScalarMult(t *testing.T) { tests := []struct { - x st - y st - k st - rx st - ry st + x string + y string + k string + rx string + ry string }{ // base mult, essentially. { @@ -636,7 +636,7 @@ func TestScalarMultRand(t *testing.T) { x, y := s256.Gx, s256.Gy exponent := big.NewInt(1) for i := 0; i < 1024; i++ { - data := make(by, 32) + data := make([]byte, 32) _, err := rand.Read(data) if err != nil { t.Fatalf("failed to read random data at %d", i) @@ -676,7 +676,7 @@ var ( // provable mathematically due to how a1/b1/a2/b2 are computed. // // c1 and c2 are chosen to minimize the max(k1,k2). -func splitK(k by) (by, by, no, no) { +func splitK(k []byte) ([]byte, []byte, int, int) { // All math here is done with big.Int, which is slow. // At some point, it might be useful to write something similar to // FieldVal but for no instead of P as the prime field if this ends up @@ -711,9 +711,9 @@ func splitK(k by) (by, by, no, no) { func TestSplitK(t *testing.T) { tests := []struct { - k st - k1, k2 st - s1, s2 no + k string + k1, k2 string + s1, s2 int }{ { "6df2b5d30854069ccdec40ae022f5c948936324a4e9ebed8eb82cfd5a6b6d766", @@ -797,7 +797,7 @@ func TestSplitK(t *testing.T) { func TestSplitKRand(t *testing.T) { s256 := S256() for i := 0; i < 1024; i++ { - bytesK := make(by, 32) + bytesK := make([]byte, 32) _, err := rand.Read(bytesK) if err != nil { t.Fatalf("failed to read random data at %d", i) @@ -822,7 +822,7 @@ func TestSplitKRand(t *testing.T) { // Test this curve's usage with the ecdsa package. -func testKeyGeneration(t *testing.T, c *KoblitzCurve, tag st) { +func testKeyGeneration(t *testing.T, c *KoblitzCurve, tag string) { priv, err := NewSecretKey() if err != nil { t.Errorf("%s: error: %s", tag, err) @@ -841,7 +841,7 @@ func TestKeyGeneration(t *testing.T) { // checkNAFEncoding returns an error if the provided positive and negative // portions of an overall NAF encoding do not adhere to the requirements or they // do not sum back to the provided original value. -func checkNAFEncoding(pos, neg by, origValue *big.Int) er { +func checkNAFEncoding(pos, neg []byte, origValue *big.Int) error { // NAF must not have a leading zero byte and the number of negative // bytes must not exceed the positive portion. if len(pos) > 0 && pos[0] == 0 { diff --git a/ec/chaincfg/deployment_time_frame.go b/ec/chaincfg/deployment_time_frame.go index 4ead930..c4fe7d3 100644 --- a/ec/chaincfg/deployment_time_frame.go +++ b/ec/chaincfg/deployment_time_frame.go @@ -19,7 +19,7 @@ var ( // passed. type ConsensusDeploymentStarter interface { // HasStarted returns true if the consensus deployment has started. - HasStarted(*wire.BlockHeader) (bo, er) + HasStarted(*wire.BlockHeader) (bool, error) } // ConsensusDeploymentEnder determines if a given consensus deployment has @@ -27,7 +27,7 @@ type ConsensusDeploymentStarter interface { // deployment is no longer eligible for activation. type ConsensusDeploymentEnder interface { // HasEnded returns true if the consensus deployment has ended. - HasEnded(*wire.BlockHeader) (bo, er) + HasEnded(*wire.BlockHeader) (bool, error) } // BlockClock is an abstraction over the past median time computation. The past @@ -39,7 +39,7 @@ type BlockClock interface { // PastMedianTime returns the past median time from the PoV of the // passed block header. The past median time is the median time of the // 11 blocks prior to the passed block header. - PastMedianTime(*wire.BlockHeader) (time.Time, er) + PastMedianTime(*wire.BlockHeader) (time.Time, error) } // ClockConsensusDeploymentEnder is a more specialized version of the @@ -74,8 +74,8 @@ func NewMedianTimeDeploymentStarter(startTime time.Time) *MedianTimeDeploymentSt } // HasStarted returns true if the consensus deployment has started. -func (m *MedianTimeDeploymentStarter) HasStarted(blkHeader *wire.BlockHeader) (bo, - er) { +func (m *MedianTimeDeploymentStarter) HasStarted(blkHeader *wire.BlockHeader) (bool, + error) { switch { // If we haven't yet been synchronized with a block clock, then we // can't tell the time, so we'll fail. @@ -112,8 +112,8 @@ func NewMedianTimeDeploymentEnder(endTime time.Time) *MedianTimeDeploymentEnder } // HasEnded returns true if the deployment has ended. -func (m *MedianTimeDeploymentEnder) HasEnded(blkHeader *wire.BlockHeader) (bo, - er) { +func (m *MedianTimeDeploymentEnder) HasEnded(blkHeader *wire.BlockHeader) (bool, + error) { switch { // If we haven't yet been synchronized with a block clock, then we can't tell // the time, so we'll we haven't yet been synchronized with a block diff --git a/ec/chaincfg/genesis.go b/ec/chaincfg/genesis.go index cccf5e1..c1e2c63 100644 --- a/ec/chaincfg/genesis.go +++ b/ec/chaincfg/genesis.go @@ -18,7 +18,7 @@ var ( Hash: chainhash.Hash{}, Index: 0xffffffff, }, - SignatureScript: by{ + SignatureScript: []byte{ 0x04, 0xff, 0xff, 0x00, 0x1d, 0x01, 0x04, 0x45, /* |.......E| */ 0x54, 0x68, 0x65, 0x20, 0x54, 0x69, 0x6d, @@ -45,7 +45,7 @@ var ( TxOut: []*wire.TxOut{ { Value: 0x12a05f200, - PkScript: by{ + PkScript: []byte{ 0x41, 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, /* |A.g....U| */ 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, diff --git a/ec/chaincfg/params.go b/ec/chaincfg/params.go index 890e038..cff718b 100644 --- a/ec/chaincfg/params.go +++ b/ec/chaincfg/params.go @@ -98,11 +98,11 @@ type Checkpoint struct { // DNSSeed identifies a DNS seed. type DNSSeed struct { // Host defines the hostname of the seed. - Host st + Host string // HasFiltering defines whether the seed supports filtering // by service flags (wire.ServiceFlag). - HasFiltering bo + HasFiltering bool } // Params defines a Bitcoin network by its parameters. These parameters may be @@ -110,13 +110,13 @@ type DNSSeed struct { // and keys for one network from those intended for use on another network. type Params struct { // Name defines a human-readable identifier for the network. - Name st + Name string // Net defines the magic bytes used to identify the network. Net wire.BitcoinNet // DefaultPort defines the default peer-to-peer port for the network. - DefaultPort st + DefaultPort string // DNSSeeds defines a list of DNS seeds for the network that are used // as one method to discover peers. @@ -139,7 +139,7 @@ type Params struct { // PoWNoRetargeting defines whether the network has difficulty // retargeting enabled or not. This should only be set to true for // regtest like networks. - PoWNoRetargeting bo + PoWNoRetargeting bool // These fields define the block heights at which the specified softfork // BIP became active. @@ -174,7 +174,7 @@ type Params struct { // minimum required difficulty after a long enough period of time has // passed without finding a block. This is really only useful for test // networks and should not be set on a main network. - ReduceMinDifficulty bo + ReduceMinDifficulty bool // MinDiffReductionTime is the amount of time after which the minimum // required difficulty should be reduced when a block hasn't been found. @@ -183,7 +183,7 @@ type Params struct { MinDiffReductionTime time.Duration // GenerateSupported specifies whether or not CPU mining is allowed. - GenerateSupported bo + GenerateSupported bool // Checkpoints ordered from oldest to newest. Checkpoints []Checkpoint @@ -206,11 +206,11 @@ type Params struct { Deployments [DefinedDeployments]ConsensusDeployment // Mempool parameters - RelayNonStdTxs bo + RelayNonStdTxs bool // Human-readable part for Bech32 encoded segwit addresses, as defined // in BIP 173. - Bech32HRPSegwit by + Bech32HRPSegwit []byte // Address encoding magics PubKeyHashAddrID byte // First byte of a P2PKH address @@ -390,7 +390,7 @@ var MainNetParams = Params{ // Human-readable part for Bech32 encoded segwit addresses, as defined in // BIP 173. - Bech32HRPSegwit: by("bc"), // always bc for main net + Bech32HRPSegwit: []byte("bc"), // always bc for main net // Address encoding magics PubKeyHashAddrID: 0x00, // starts with 1 @@ -412,7 +412,7 @@ var MainNetParams = Params{ // chainhash.Hash. It only differs from the one available in chainhash in that // it panics on an error since it will only (and must only) be called with // hard-coded, and therefore known good, hashes. -func newHashFromStr(hexStr st) *chainhash.Hash { +func newHashFromStr(hexStr string) *chainhash.Hash { hash, err := chainhash.NewHashFromStr(hexStr) if err != nil { // Ordinarily I don't like panics in library code since it diff --git a/ec/chaincfg/util.go b/ec/chaincfg/util.go index ed870b6..3d88765 100644 --- a/ec/chaincfg/util.go +++ b/ec/chaincfg/util.go @@ -1,22 +1,9 @@ package chaincfg import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/chainhash/hash.go b/ec/chainhash/hash.go index ec573c4..9e684fe 100644 --- a/ec/chainhash/hash.go +++ b/ec/chainhash/hash.go @@ -22,27 +22,27 @@ const ( var ( // TagBIP0340Challenge is the BIP-0340 tag for challenges. - TagBIP0340Challenge = by("BIP0340/challenge") + TagBIP0340Challenge = []byte("BIP0340/challenge") // TagBIP0340Aux is the BIP-0340 tag for aux data. - TagBIP0340Aux = by("BIP0340/aux") + TagBIP0340Aux = []byte("BIP0340/aux") // TagBIP0340Nonce is the BIP-0340 tag for nonces. - TagBIP0340Nonce = by("BIP0340/nonce") + TagBIP0340Nonce = []byte("BIP0340/nonce") // TagTapSighash is the tag used by BIP 341 to generate the sighash // flags. - TagTapSighash = by("TapSighash") + TagTapSighash = []byte("TapSighash") // TagTapLeaf is the message tag prefix used to compute the hash // digest of a tapscript leaf. - TagTapLeaf = by("TapLeaf") + TagTapLeaf = []byte("TapLeaf") // TagTapBranch is the message tag prefix used to compute the // hash digest of two tap leaves into a taproot branch node. - TagTapBranch = by("TapBranch") + TagTapBranch = []byte("TapBranch") // TagTapTweak is the message tag prefix used to compute the hash tweak // used to enable a public key to commit to the taproot branch root // for the witness program. - TagTapTweak = by("TapTweak") + TagTapTweak = []byte("TapTweak") // precomputedTags is a map containing the SHA-256 hash of the BIP-0340 // tags. - precomputedTags = map[st]Hash{ + precomputedTags = map[string]Hash{ string(TagBIP0340Challenge): sha256.Sum256(TagBIP0340Challenge), string(TagBIP0340Aux): sha256.Sum256(TagBIP0340Aux), string(TagBIP0340Nonce): sha256.Sum256(TagBIP0340Nonce), @@ -76,15 +76,15 @@ func (hash Hash) String() string { // // NOTE: It is generally cheaper to just slice the hash directly thereby reusing // the same bytes rather than calling this method. -func (hash *Hash) CloneBytes() by { - newHash := make(by, HashSize) +func (hash *Hash) CloneBytes() []byte { + newHash := make([]byte, HashSize) copy(newHash, hash[:]) return newHash } // SetBytes sets the bytes which represent the hash. An error is returned if // the number of bytes passed in is not HashSize. -func (hash *Hash) SetBytes(newHash by) er { +func (hash *Hash) SetBytes(newHash []byte) error { nhlen := len(newHash) if nhlen != HashSize { return fmt.Errorf("invalid hash length of %v, want %v", nhlen, @@ -95,7 +95,7 @@ func (hash *Hash) SetBytes(newHash by) er { } // IsEqual returns true if target is the same as hash. -func (hash *Hash) IsEqual(target *Hash) bo { +func (hash *Hash) IsEqual(target *Hash) bool { if hash == nil && target == nil { return true } @@ -106,12 +106,12 @@ func (hash *Hash) IsEqual(target *Hash) bo { } // MarshalJSON serialises the hash as a JSON appropriate string value. -func (hash Hash) MarshalJSON() (by, er) { +func (hash Hash) MarshalJSON() ([]byte, error) { return json.Marshal(hash.String()) } // UnmarshalJSON parses the hash with JSON appropriate string value. -func (hash *Hash) UnmarshalJSON(input by) er { +func (hash *Hash) UnmarshalJSON(input []byte) error { // If the first byte indicates an array, the hash could have been marshalled // using the legacy method and e.g. persisted. if len(input) > 0 && input[0] == '[' { @@ -131,7 +131,7 @@ func (hash *Hash) UnmarshalJSON(input by) er { // NewHash returns a new Hash from a byte slice. An error is returned if // the number of bytes passed in is not HashSize. -func NewHash(newHash by) (*Hash, er) { +func NewHash(newHash []byte) (*Hash, error) { var sh Hash err := sh.SetBytes(newHash) if err != nil { @@ -143,7 +143,7 @@ func NewHash(newHash by) (*Hash, er) { // TaggedHash implements the tagged hash scheme described in BIP-340. We use // sha-256 to bind a message hash to a specific context using a tag: // sha256(sha256(tag) || sha256(tag) || msg). -func TaggedHash(tag by, msgs ...by) *Hash { +func TaggedHash(tag []byte, msgs ...[]byte) *Hash { // Check to see if we've already pre-computed the hash of the tag. If // so then this'll save us an extra sha256 hash. shaTag, ok := precomputedTags[string(tag)] @@ -167,7 +167,7 @@ func TaggedHash(tag by, msgs ...by) *Hash { // NewHashFromStr creates a Hash from a hash string. The string should be // the hexadecimal string of a byte-reversed hash, but any missing characters // result in zero padding at the end of the Hash. -func NewHashFromStr(hash string) (*Hash, er) { +func NewHashFromStr(hash string) (*Hash, error) { ret := new(Hash) err := Decode(ret, hash) if err != nil { @@ -178,18 +178,18 @@ func NewHashFromStr(hash string) (*Hash, er) { // Decode decodes the byte-reversed hexadecimal string encoding of a Hash to a // destination. -func Decode(dst *Hash, src string) er { +func Decode(dst *Hash, src string) error { // Return error if hash string is too long. if len(src) > MaxHashStringSize { return ErrHashStrSize } // Hex decoder expects the hash to be a multiple of two. When not, pad // with a leading zero. - var srcBytes by + var srcBytes []byte if len(src)%2 == 0 { - srcBytes = by(src) + srcBytes = []byte(src) } else { - srcBytes = make(by, 1+len(src)) + srcBytes = make([]byte, 1+len(src)) srcBytes[0] = '0' copy(srcBytes[1:], src) } @@ -210,8 +210,8 @@ func Decode(dst *Hash, src string) er { // decodeLegacy decodes an Hash that has been encoded with the legacy method // (i.e. represented as a bytes array) to a destination. -func decodeLegacy(dst *Hash, src by) er { - var hashBytes by +func decodeLegacy(dst *Hash, src []byte) error { + var hashBytes []byte err := json.Unmarshal(src, &hashBytes) if err != nil { return err diff --git a/ec/chainhash/hash_test.go b/ec/chainhash/hash_test.go index 36a41b3..92a4456 100644 --- a/ec/chainhash/hash_test.go +++ b/ec/chainhash/hash_test.go @@ -5,6 +5,7 @@ package chainhash import ( + "bytes" "testing" ) @@ -26,7 +27,7 @@ func TestHash(t *testing.T) { t.Errorf("NewHashFromStr: %v", err) } // Hash of block 234440 as byte slice. - buf := by{ + buf := []byte{ 0x79, 0xa6, 0x1a, 0xdb, 0xc6, 0xe5, 0xa2, 0xe1, 0x39, 0xd2, 0x71, 0x3a, 0x54, 0x6e, 0xc7, 0xc8, 0x75, 0x63, 0x2e, 0x75, 0xf1, 0xdf, 0x9c, 0x3f, @@ -42,7 +43,7 @@ func TestHash(t *testing.T) { len(hash), HashSize) } // Ensure contents match. - if !equals(hash[:], buf) { + if !bytes.Equal(hash[:], buf) { t.Errorf("NewHash: hash contents mismatch - got: %v, want: %v", hash[:], buf) } @@ -68,12 +69,12 @@ func TestHash(t *testing.T) { t.Error("IsEqual: non-nil hash matches nil hash") } // Invalid size for SetBytes. - err = hash.SetBytes(by{0x00}) + err = hash.SetBytes([]byte{0x00}) if err == nil { t.Errorf("SetBytes: failed to received expected err - got: nil") } // Invalid size for NewHash. - invalidHash := make(by, HashSize+1) + invalidHash := make([]byte, HashSize+1) _, err = NewHash(invalidHash) if err == nil { t.Errorf("NewHash: failed to received expected err - got: nil") diff --git a/ec/chainhash/hashfuncs.go b/ec/chainhash/hashfuncs.go index ee19d16..b039506 100644 --- a/ec/chainhash/hashfuncs.go +++ b/ec/chainhash/hashfuncs.go @@ -8,16 +8,16 @@ package chainhash import "realy.lol/sha256" // HashB calculates hash(b) and returns the resulting bytes. -func HashB(b by) by { +func HashB(b []byte) []byte { hash := sha256.Sum256(b) return hash[:] } // HashH calculates hash(b) and returns the resulting bytes as a Hash. -func HashH(b by) Hash { return Hash(sha256.Sum256(b)) } +func HashH(b []byte) Hash { return Hash(sha256.Sum256(b)) } // DoubleHashB calculates hash(hash(b)) and returns the resulting bytes. -func DoubleHashB(b by) by { +func DoubleHashB(b []byte) []byte { first := sha256.Sum256(b) second := sha256.Sum256(first[:]) return second[:] @@ -25,7 +25,7 @@ func DoubleHashB(b by) by { // DoubleHashH calculates hash(hash(b)) and returns the resulting bytes as a // Hash. -func DoubleHashH(b by) Hash { +func DoubleHashH(b []byte) Hash { first := sha256.Sum256(b) return sha256.Sum256(first[:]) } diff --git a/ec/chainhash/hashfuncs_test.go b/ec/chainhash/hashfuncs_test.go index 7a0c0ac..e9c2d53 100644 --- a/ec/chainhash/hashfuncs_test.go +++ b/ec/chainhash/hashfuncs_test.go @@ -13,8 +13,8 @@ import ( // expected. func TestHashFuncs(t *testing.T) { tests := []struct { - out st - in st + out string + in string }{ {"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ""}, @@ -83,7 +83,7 @@ func TestHashFuncs(t *testing.T) { // Ensure the hash function which returns a byte slice returns the // expected result. for _, test := range tests { - h := fmt.Sprintf("%x", HashB(by(test.in))) + h := fmt.Sprintf("%x", HashB([]byte(test.in))) if h != test.out { t.Errorf("HashB(%q) = %s, want %s", test.in, h, test.out) continue @@ -92,7 +92,7 @@ func TestHashFuncs(t *testing.T) { // Ensure the hash function which returns a Hash returns the expected // result. for _, test := range tests { - hash := HashH(by(test.in)) + hash := HashH([]byte(test.in)) h := fmt.Sprintf("%x", hash[:]) if h != test.out { t.Errorf("HashH(%q) = %s, want %s", test.in, h, test.out) @@ -105,8 +105,8 @@ func TestHashFuncs(t *testing.T) { // work as expected. func TestDoubleHashFuncs(t *testing.T) { tests := []struct { - out st - in st + out string + in string }{ {"5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", ""}, @@ -174,7 +174,7 @@ func TestDoubleHashFuncs(t *testing.T) { // Ensure the hash function which returns a byte slice returns the // expected result. for _, test := range tests { - h := fmt.Sprintf("%x", DoubleHashB(by(test.in))) + h := fmt.Sprintf("%x", DoubleHashB([]byte(test.in))) if h != test.out { t.Errorf("DoubleHashB(%q) = %s, want %s", test.in, h, test.out) @@ -184,7 +184,7 @@ func TestDoubleHashFuncs(t *testing.T) { // Ensure the hash function which returns a Hash returns the expected // result. for _, test := range tests { - hash := DoubleHashH(by(test.in)) + hash := DoubleHashH([]byte(test.in)) h := fmt.Sprintf("%x", hash[:]) if h != test.out { t.Errorf("DoubleHashH(%q) = %s, want %s", test.in, h, diff --git a/ec/chainhash/util.go b/ec/chainhash/util.go index e5f4a8f..d4a5534 100644 --- a/ec/chainhash/util.go +++ b/ec/chainhash/util.go @@ -1,22 +1,9 @@ package chainhash import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/ciphering.go b/ec/ciphering.go index 279d3a6..e952339 100644 --- a/ec/ciphering.go +++ b/ec/ciphering.go @@ -11,6 +11,6 @@ import ( // GenerateSharedSecret generates a shared secret based on a secret key and a // public key using Diffie-Hellman key exchange (ECDH) (RFC 4753). // RFC5903 Section 9 states we should only return x. -func GenerateSharedSecret(privkey *SecretKey, pubkey *PublicKey) by { +func GenerateSharedSecret(privkey *SecretKey, pubkey *PublicKey) []byte { return secp256k1.GenerateSharedSecret(privkey, pubkey) } diff --git a/ec/curve.go b/ec/curve.go index bc81d7b..33a701e 100644 --- a/ec/curve.go +++ b/ec/curve.go @@ -35,7 +35,7 @@ func AddNonConst(p1, p2, result *JacobianPoint) { // // The magnitude of the provided X coordinate field val must be a max of 8 for // a correct result. The resulting Y field val will have a max magnitude of 2. -func DecompressY(x *FieldVal, odd bo, resultY *FieldVal) bo { +func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool { return secp256k1.DecompressY(x, odd, resultY) } @@ -70,7 +70,7 @@ func ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) { // ParseJacobian parses a byte slice point as a secp256k1.Publickey and returns the // pubkey as a JacobianPoint. If the nonce is a zero slice, the infinityPoint // is returned. -func ParseJacobian(point by) (JacobianPoint, er) { +func ParseJacobian(point []byte) (JacobianPoint, error) { var result JacobianPoint if len(point) != 33 { str := fmt.Sprintf("invalid nonce: invalid length: %v", @@ -91,9 +91,9 @@ func ParseJacobian(point by) (JacobianPoint, er) { // JacobianToByteSlice converts the passed JacobianPoint to a Pubkey // and serializes that to a byte slice. If the JacobianPoint is the infinity // point, a zero slice is returned. -func JacobianToByteSlice(point JacobianPoint) by { +func JacobianToByteSlice(point JacobianPoint) []byte { if point.X == infinityPoint.X && point.Y == infinityPoint.Y { - return make(by, 33) + return make([]byte, 33) } point.ToAffine() return NewPublicKey( diff --git a/ec/ecdsa/bench_test.go b/ec/ecdsa/bench_test.go index 1c3abb1..997abf4 100644 --- a/ec/ecdsa/bench_test.go +++ b/ec/ecdsa/bench_test.go @@ -16,7 +16,7 @@ import ( // panic if there is an error. This is only provided for the hard-coded // constants so errors in the source code can be detected. It will only (and // must only) be called with hard-coded values. -func hexToModNScalar(s st) *secp256k1.ModNScalar { +func hexToModNScalar(s string) *secp256k1.ModNScalar { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -32,7 +32,7 @@ func hexToModNScalar(s st) *secp256k1.ModNScalar { // if there is an error. This is only provided for the hard-coded constants so // errors in the source code can be detected. It will only (and must only) be // called with hard-coded values. -func hexToFieldVal(s st) *secp256k1.FieldVal { +func hexToFieldVal(s string) *secp256k1.FieldVal { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) diff --git a/ec/ecdsa/error.go b/ec/ecdsa/error.go index 3d6f936..08b8c6e 100644 --- a/ec/ecdsa/error.go +++ b/ec/ecdsa/error.go @@ -7,7 +7,7 @@ package ecdsa // ErrorKind identifies a kind of error. It has full support for // errors.Is and errors.As, so the caller can directly check against // an error kind when determining the reason for an error. -type ErrorKind st +type ErrorKind string // These constants are used to identify a specific Error. const ( @@ -84,23 +84,23 @@ const ( ) // Error satisfies the error interface and prints human-readable errors. -func (e ErrorKind) Error() st { return st(e) } +func (e ErrorKind) Error() string { return string(e) } // Error identifies an error related to an ECDSA signature. It has full // support for errors.Is and errors.As, so the caller can ascertain the // specific reason for the error by checking the underlying error. type Error struct { - Err er - Description st + Err error + Description string } // Error satisfies the error interface and prints human-readable errors. -func (e Error) Error() st { return e.Description } +func (e Error) Error() string { return e.Description } // Unwrap returns the underlying wrapped error. -func (e Error) Unwrap() er { return e.Err } +func (e Error) Unwrap() error { return e.Err } // signatureError creates an Error given a set of arguments. -func signatureError(kind ErrorKind, desc st) Error { +func signatureError(kind ErrorKind, desc string) Error { return Error{Err: kind, Description: desc} } diff --git a/ec/ecdsa/error_test.go b/ec/ecdsa/error_test.go index df30e4c..2a4d4f4 100644 --- a/ec/ecdsa/error_test.go +++ b/ec/ecdsa/error_test.go @@ -13,7 +13,7 @@ import ( func TestErrorKindStringer(t *testing.T) { tests := []struct { in ErrorKind - want st + want string }{ {ErrSigTooShort, "ErrSigTooShort"}, {ErrSigTooLong, "ErrSigTooLong"}, @@ -53,7 +53,7 @@ func TestErrorKindStringer(t *testing.T) { func TestError(t *testing.T) { tests := []struct { in Error - want st + want string }{{ Error{Description: "some error"}, "some error", @@ -74,10 +74,10 @@ func TestError(t *testing.T) { // a specific error kind via errors.Is and unwrapped via errors.As. func TestErrorKindIsAs(t *testing.T) { tests := []struct { - name st - err er - target er - wantMatch bo + name string + err error + target error + wantMatch bool wantAs ErrorKind }{{ name: "ErrSigTooShort == ErrSigTooShort", diff --git a/ec/ecdsa/signature.go b/ec/ecdsa/signature.go index b57b984..fa04c37 100644 --- a/ec/ecdsa/signature.go +++ b/ec/ecdsa/signature.go @@ -63,7 +63,7 @@ func NewSignature(r, s *secp256k1.ModNScalar) *Signature { // // Note that the serialized bytes returned do not include the appended hash type // used in Decred signature scripts. -func (sig *Signature) Serialize() by { +func (sig *Signature) Serialize() []byte { // The format of a DER encoded signature is as follows: // // 0x30 0x02 0x02 @@ -112,7 +112,7 @@ func (sig *Signature) Serialize() by { // Total length of returned signature is 1 byte for each magic and length // (6 total), plus lengths of R and S. totalLen := 6 + len(canonR) + len(canonS) - b := make(by, 0, totalLen) + b := make([]byte, 0, totalLen) b = append(b, asn1SequenceID) b = append(b, byte(totalLen-2)) b = append(b, asn1IntegerID) @@ -156,7 +156,7 @@ func modNScalarToField(v *secp256k1.ModNScalar) secp256k1.FieldVal { // Verify returns whether the signature is valid for the provided hash // and secp256k1 public key. -func (sig *Signature) Verify(hash by, pubKey *secp256k1.PublicKey) bo { +func (sig *Signature) Verify(hash []byte, pubKey *secp256k1.PublicKey) bool { // The algorithm for verifying an ECDSA signature is given as algorithm 4.30 // in [GECC]. // @@ -277,7 +277,7 @@ func (sig *Signature) Verify(hash by, pubKey *secp256k1.PublicKey) bo { // IsEqual compares this Signature instance to the one passed, returning true if // both Signatures are equivalent. A signature is equivalent to another, if // they both have the same scalar value for R and S. -func (sig *Signature) IsEqual(otherSig *Signature) bo { +func (sig *Signature) IsEqual(otherSig *Signature) bool { return sig.r.Equals(&otherSig.r) && sig.s.Equals(&otherSig.s) } @@ -289,7 +289,7 @@ func (sig *Signature) IsEqual(otherSig *Signature) bo { // - Negative values are rejected // - Zero is rejected // - Values greater than or equal to the secp256k1 group order are rejected -func ParseDERSignature(sig by) (*Signature, er) { +func ParseDERSignature(sig []byte) (*Signature, error) { // The format of a DER encoded signature for secp256k1 is as follows: // // 0x30 0x02 0x02 @@ -360,7 +360,7 @@ func ParseDERSignature(sig by) (*Signature, er) { } // The signature must indicate the correct amount of data for all elements // related to R and S. - if no(sig[dataLenOffset]) != sigLen-2 { + if int(sig[dataLenOffset]) != sigLen-2 { str := fmt.Sprintf("malformed signature: bad length: %d != %d", sig[dataLenOffset], sigLen-2) return nil, signatureError(ErrSigInvalidDataLen, str) @@ -376,7 +376,7 @@ func ParseDERSignature(sig by) (*Signature, er) { // // sLenOffset and sOffset are the byte offsets within the signature of the // length of S and S itself, respectively. - rLen := no(sig[rLenOffset]) + rLen := int(sig[rLenOffset]) sTypeOffset := rOffset + rLen sLenOffset := sTypeOffset + 1 if sTypeOffset >= sigLen { @@ -392,7 +392,7 @@ func ParseDERSignature(sig by) (*Signature, er) { // sLen specifies the length of the big-endian encoded number which // represents the S value of the signature. sOffset := sLenOffset + 1 - sLen := no(sig[sLenOffset]) + sLen := int(sig[sLenOffset]) if sOffset+sLen != sigLen { str := "malformed signature: invalid S length" return nil, signatureError(ErrSigInvalidSLen, str) @@ -508,8 +508,8 @@ func ParseDERSignature(sig by) (*Signature, er) { // signing logic. It differs in that it accepts a nonce to use when signing and // may not successfully produce a valid signature for the given nonce. It is // primarily separated for testing purposes. -func sign(secKey, nonce *secp256k1.ModNScalar, hash by) (*Signature, byte, - bo) { +func sign(secKey, nonce *secp256k1.ModNScalar, hash []byte) (*Signature, byte, + bool) { // The algorithm for producing an ECDSA signature is given as algorithm 4.29 // in [GECC]. // @@ -617,7 +617,7 @@ func sign(secKey, nonce *secp256k1.ModNScalar, hash by) (*Signature, byte, // signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 // and BIP0062 and returns it along with an additional public key recovery code // for efficiently recovering the public key from the signature. -func signRFC6979(secKey *secp256k1.SecretKey, hash by) (*Signature, +func signRFC6979(secKey *secp256k1.SecretKey, hash []byte) (*Signature, byte) { // The algorithm for producing an ECDSA signature is given as algorithm 4.29 // in [GECC]. @@ -674,7 +674,7 @@ func signRFC6979(secKey *secp256k1.SecretKey, hash by) (*Signature, // secret key. The produced signature is deterministic (same message and same // key yield the same signature) and canonical in accordance with RFC6979 and // BIP0062. -func Sign(key *secp256k1.SecretKey, hash by) *Signature { +func Sign(key *secp256k1.SecretKey, hash []byte) *Signature { signature, _ := signRFC6979(key, hash) return signature } @@ -714,8 +714,8 @@ const ( // // The compact sig recovery code is the value 27 + public key recovery code + 4 // if the compact signature was created with a compressed public key. -func SignCompact(key *secp256k1.SecretKey, hash by, - isCompressedKey bo) by { +func SignCompact(key *secp256k1.SecretKey, hash []byte, + isCompressedKey bool) []byte { // Create the signature and associated pubkey recovery code and calculate // the compact signature recovery code. sig, pubKeyRecoveryCode := signRFC6979(key, hash) @@ -735,7 +735,7 @@ func SignCompact(key *secp256k1.SecretKey, hash by, // compact signature and message hash. It first verifies the signature, and, if // the signature matches then the recovered public key will be returned as well // as a boolean indicating whether or not the original key was compressed. -func RecoverCompact(signature, hash by) (*secp256k1.PublicKey, bo, er) { +func RecoverCompact(signature, hash []byte) (*secp256k1.PublicKey, bool, error) { // The following is very loosely based on the information and algorithm that // describes recovering a public key from and ECDSA signature in section // 4.1.6 of [SEC1]. diff --git a/ec/ecdsa/signature_test.go b/ec/ecdsa/signature_test.go index ffcadcb..cffc6b2 100644 --- a/ec/ecdsa/signature_test.go +++ b/ec/ecdsa/signature_test.go @@ -9,6 +9,7 @@ package ecdsa import ( + "bytes" "errors" "math/rand" "testing" @@ -22,7 +23,7 @@ import ( // is an error. This is only provided for the hard-coded constants so errors in // the source code can be detected. It will only (and must only) be called with // hard-coded values. -func hexToBytes(s st) by { +func hexToBytes(s string) []byte { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -34,9 +35,9 @@ func hexToBytes(s st) by { // to DER rules. The error paths are tested as well. func TestSignatureParsing(t *testing.T) { tests := []struct { - name st - sig by - err er + name string + sig []byte + err error }{{ // signature from Decred blockchain tx // 76634e947f49dfc6228c3e8a09cd3e9e15893439fc06df7df0fc6f08d659856c:0 @@ -213,9 +214,9 @@ func TestSignatureParsing(t *testing.T) { // TestSignatureSerialize ensures that serializing signatures works as expected. func TestSignatureSerialize(t *testing.T) { tests := []struct { - name st + name string ecsig *Signature - expected by + expected []byte }{{ // signature from bitcoin blockchain tx // 0437cd7f8525ceed2324359c2d0ba26006d92d85 @@ -263,7 +264,7 @@ func TestSignatureSerialize(t *testing.T) { }} for i, test := range tests { result := test.ecsig.Serialize() - if !equals(result, test.expected) { + if !bytes.Equal(result, test.expected) { t.Errorf("Serialize #%d (%s) unexpected result:\n"+ "got: %x\nwant: %x", i, test.name, result, test.expected) @@ -277,15 +278,15 @@ func TestSignatureSerialize(t *testing.T) { // separately since it is intended for use in both normal and compact signature // tests. type signTest struct { - name st // test description - key st // hex encoded secret key - msg st // hex encoded message to sign before hashing - hash st // hex encoded hash of the message to sign - nonce st // hex encoded nonce to use in the signature calculation - rfc6979 bo // whether the nonce is an RFC6979 nonce - wantSigR st // hex encoded expected signature R - wantSigS st // hex encoded expected signature S - wantCode byte // expected public key recovery code + name string // test description + key string // hex encoded secret key + msg string // hex encoded message to sign before hashing + hash string // hex encoded hash of the message to sign + nonce string // hex encoded nonce to use in the signature calculation + rfc6979 bool // whether the nonce is an RFC6979 nonce + wantSigR string // hex encoded expected signature R + wantSigS string // hex encoded expected signature S + wantCode byte // expected public key recovery code } // // signTests returns several tests for ECDSA signatures that use a selected set @@ -628,7 +629,7 @@ func TestSignAndVerifyRandom(t *testing.T) { } // Change a random bit in the hash that was originally signed and ensure // the original good signature fails to verify the new bad message. - badHash := make(by, len(hash)) + badHash := make([]byte, len(hash)) copy(badHash, hash[:]) randByte = rng.Intn(len(badHash)) randBit = rng.Intn(7) @@ -647,10 +648,10 @@ func TestSignAndVerifyRandom(t *testing.T) { func TestSignFailures(t *testing.T) { t.Parallel() tests := []struct { - name st // test description - key st // hex encoded secret key - hash st // hex encoded hash of the message to sign - nonce st // hex encoded nonce to use in the signature calculation + name string // test description + key string // hex encoded secret key + hash string // hex encoded hash of the message to sign + nonce string // hex encoded nonce to use in the signature calculation }{{ name: "zero R is invalid (forced by using zero nonce)", key: "0000000000000000000000000000000000000000000000000000000000000001", @@ -682,10 +683,10 @@ func TestVerifyFailures(t *testing.T) { t.Parallel() tests := []struct { - name st // test description - key st // hex encoded secret key - hash st // hex encoded hash of the message to sign - r, s st // hex encoded r and s components of signature to verify + name string // test description + key string // hex encoded secret key + hash string // hex encoded hash of the message to sign + r, s string // hex encoded r and s components of signature to verify }{{ name: "signature R is 0", key: "0000000000000000000000000000000000000000000000000000000000000001", @@ -825,10 +826,10 @@ func TestRecoverCompactErrors(t *testing.T) { t.Parallel() tests := []struct { - name st // test description - sig st // hex encoded signature to recover pubkey from - hash st // hex encoded hash of message - err er // expected error + name string // test description + sig string // hex encoded signature to recover pubkey from + hash string // hex encoded hash of message + err error // expected error }{{ name: "empty signature", sig: "", @@ -999,7 +1000,7 @@ func TestSignAndRecoverCompactRandom(t *testing.T) { } // Test compact signatures for both the compressed and uncompressed // versions of the public key. - for _, compressed := range []bo{true, false} { + for _, compressed := range []bool{true, false} { // Sign the hash with the secret key and then ensure the original // public key and compressed flag is recovered from the produced // signature. @@ -1022,7 +1023,7 @@ func TestSignAndRecoverCompactRandom(t *testing.T) { } // Change a random bit in the signature and ensure the bad signature // fails to recover the original public key. - badSig := make(by, len(gotSig)) + badSig := make([]byte, len(gotSig)) copy(badSig, gotSig) randByte := rng.Intn(len(badSig)-1) + 1 randBit := rng.Intn(7) @@ -1035,7 +1036,7 @@ func TestSignAndRecoverCompactRandom(t *testing.T) { // Change a random bit in the hash that was originally signed and // ensure the original good signature fails to recover the original // public key. - badHash := make(by, len(hash)) + badHash := make([]byte, len(hash)) copy(badHash, hash[:]) randByte = rng.Intn(len(badHash)) randBit = rng.Intn(7) diff --git a/ec/ecdsa/util.go b/ec/ecdsa/util.go index ff5b50a..9d5f8d7 100644 --- a/ec/ecdsa/util.go +++ b/ec/ecdsa/util.go @@ -1,22 +1,9 @@ package ecdsa import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/ecdsa/util_test.go b/ec/ecdsa/util_test.go index e59dd35..6fee6f4 100644 --- a/ec/ecdsa/util_test.go +++ b/ec/ecdsa/util_test.go @@ -1,22 +1,9 @@ package ecdsa_test import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/error.go b/ec/error.go index f817982..6bd4b59 100644 --- a/ec/error.go +++ b/ec/error.go @@ -19,6 +19,6 @@ type Error = secp256k1.Error type ErrorKind = secp256k1.ErrorKind // makeError creates an secp256k1.Error given a set of arguments. -func makeError(kind ErrorKind, desc st) Error { +func makeError(kind ErrorKind, desc string) Error { return Error{Err: kind, Description: desc} } diff --git a/ec/field_test.go b/ec/field_test.go index 316be15..e4a755b 100644 --- a/ec/field_test.go +++ b/ec/field_test.go @@ -34,8 +34,8 @@ func TestIsZero(t *testing.T) { // TestStringer ensures the stringer returns the appropriate hex string. func TestStringer(t *testing.T) { tests := []struct { - in st - expected st + in string + expected string }{ {"0", "0000000000000000000000000000000000000000000000000000000000000000"}, @@ -350,8 +350,8 @@ func TestNormalize(t *testing.T) { // TestIsOdd ensures that checking if a field value IsOdd works as expected. func TestIsOdd(t *testing.T) { tests := []struct { - in st // hex encoded value - expected bo // expected oddness + in string // hex encoded value + expected bool // expected oddness }{ {"0", false}, {"1", true}, @@ -381,9 +381,9 @@ func TestIsOdd(t *testing.T) { // works as expected. func TestEquals(t *testing.T) { tests := []struct { - in1 st // hex encoded value - in2 st // hex encoded value - expected bo // expected equality + in1 string // hex encoded value + in2 string // hex encoded value + expected bool // expected equality }{ {"0", "0", true}, {"0", "1", false}, @@ -418,8 +418,8 @@ func TestEquals(t *testing.T) { // TestNegate ensures that negating field values via Negate works as expected. func TestNegate(t *testing.T) { tests := []struct { - in st // hex encoded value - expected st // expected hex encoded value + in string // hex encoded value + expected string // expected hex encoded value }{ // secp256k1 prime (aka 0) {"0", "0"}, @@ -472,10 +472,10 @@ func TestNegate(t *testing.T) { // works as expected. func TestFieldAddInt(t *testing.T) { tests := []struct { - name st // test description - in1 st // hex encoded value + name string // test description + in1 string // hex encoded value in2 uint16 // unsigned integer to add to the value above - expected st // expected hex encoded value + expected string // expected hex encoded value }{{ name: "zero + one", in1: "0", @@ -538,10 +538,10 @@ func TestFieldAddInt(t *testing.T) { // works as expected. func TestFieldAdd(t *testing.T) { tests := []struct { - name st // test description - in1 st // first hex encoded value - in2 st // second hex encoded value to add - expected st // expected hex encoded value + name string // test description + in1 string // first hex encoded value + in2 string // second hex encoded value to add + expected string // expected hex encoded value }{{ name: "zero + one", in1: "0", @@ -631,10 +631,10 @@ func TestFieldAdd(t *testing.T) { // MulInt works as expected. func TestFieldMulInt(t *testing.T) { tests := []struct { - name st // test description - in1 st // hex encoded value - in2 uint8 // unsigned integer to multiply with value above - expected st // expected hex encoded value + name string // test description + in1 string // hex encoded value + in2 uint8 // unsigned integer to multiply with value above + expected string // expected hex encoded value }{{ name: "zero * zero", in1: "0", @@ -710,10 +710,10 @@ func TestFieldMulInt(t *testing.T) { // as expected. func TestFieldMul(t *testing.T) { tests := []struct { - name st // test description - in1 st // first hex encoded value - in2 st // second hex encoded value to multiply with - expected st // expected hex encoded value + name string // test description + in1 string // first hex encoded value + in2 string // second hex encoded value to multiply with + expected string // expected hex encoded value }{{ name: "zero * zero", in1: "0", @@ -802,9 +802,9 @@ func TestFieldMul(t *testing.T) { // works as expected. func TestFieldSquare(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded value - expected st // expected hex encoded value + name string // test description + in string // hex encoded value + expected string // expected hex encoded value }{{ name: "zero", in: "0", @@ -868,8 +868,8 @@ func TestFieldSquare(t *testing.T) { // as expected. func TestInverse(t *testing.T) { tests := []struct { - in st // hex encoded value - expected st // expected hex encoded value + in string // hex encoded value + expected string // expected hex encoded value }{ // secp256k1 prime (aka 0) {"0", "0"}, @@ -936,10 +936,10 @@ func randFieldVal(t *testing.T, rng *rand.Rand) *FieldVal { // via SquareRootVal works as expected for edge cases. func TestFieldSquareRoot(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded value - valid bo // whether or not the value has a square root - want st // expected hex encoded value + name string // test description + in string // hex encoded value + valid bool // whether or not the value has a square root + want string // expected hex encoded value }{{ name: "secp256k1 prime (as 0 in and out)", in: "0", @@ -1032,7 +1032,7 @@ func TestFieldSquareRoot(t *testing.T) { // is an error. This is only provided for the hard-coded constants so errors in // the source code can be detected. It will only (and must only) be called with // hard-coded values. -func hexToBytes(s st) by { +func hexToBytes(s string) []byte { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) diff --git a/ec/fuzz_test.go b/ec/fuzz_test.go index 5132c1a..a6b85e7 100644 --- a/ec/fuzz_test.go +++ b/ec/fuzz_test.go @@ -22,7 +22,7 @@ func FuzzParsePubKey(f *testing.F) { } } // 2. Seeds from recovery tests. - var recoveryTestPubKeys = []st{ + var recoveryTestPubKeys = []string{ "04E32DF42865E97135ACFB65F3BAE71BDC86F4D49150AD6A440B6F15878109880A0A2B2667F7E725CEEA70C673093BF67663E0312623C8E091B13CF2C0F11EF652", "04A7640409AA2083FDAD38B2D8DE1263B2251799591D840653FB02DBBA503D7745FCB83D80E08A1E02896BE691EA6AFFB8A35939A646F1FC79052A744B1C82EDC3", } @@ -34,7 +34,7 @@ func FuzzParsePubKey(f *testing.F) { f.Add(seed) } // Now run the fuzzer. - f.Fuzz(func(t *testing.T, input by) { + f.Fuzz(func(t *testing.T, input []byte) { key, err := ParsePubKey(input) if key == nil && err == nil { panic("key==nil && err==nil") diff --git a/ec/hex/aliases.go b/ec/hex/aliases.go deleted file mode 100644 index 04ce26b..0000000 --- a/ec/hex/aliases.go +++ /dev/null @@ -1,33 +0,0 @@ -package hex - -import ( - "encoding/hex" - - "github.com/templexxx/xhex" -) - -var Enc = hex.EncodeToString -var EncBytes = hex.Encode -var Dec = hex.DecodeString -var DecBytes = hex.Decode - -// var EncAppend = hex.AppendEncode -// var DecAppend = hex.AppendDecode - -var DecLen = hex.DecodedLen - -type InvalidByteError = hex.InvalidByteError - -func EncAppend(dst, src by) (b by) { - l := len(dst) - dst = append(dst, make(by, len(src)*2)...) - xhex.Encode(dst[l:], src) - return dst -} - -func DecAppend(dst, src by) (b by, err er) { - l := len(dst) - dst = append(dst, make(by, len(src)/2)...) - err = xhex.Decode(dst[l:], src) - return -} diff --git a/ec/hex/util.go b/ec/hex/util.go deleted file mode 100644 index 90abbeb..0000000 --- a/ec/hex/util.go +++ /dev/null @@ -1,22 +0,0 @@ -package hex - -import ( - "bytes" - - "realy.lol/context" - "realy.lol/lol" -) - -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - -var ( - log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal -) diff --git a/ec/modnscalar.go b/ec/modnscalar.go index 56e8364..f47ce77 100644 --- a/ec/modnscalar.go +++ b/ec/modnscalar.go @@ -38,7 +38,7 @@ type ModNScalar = secp256k1.ModNScalar // that results in a valid signature in the extremely unlikely event the // original nonce produced results in an invalid signature (e.g. R == 0). // Signing code should start with 0 and increment it if necessary. -func NonceRFC6979(privKey by, hash by, extra by, version by, +func NonceRFC6979(privKey []byte, hash []byte, extra []byte, version []byte, extraIterations uint32) *ModNScalar { return secp256k1.NonceRFC6979(privKey, hash, extra, version, diff --git a/ec/musig2/bench_test.go b/ec/musig2/bench_test.go index 1ddadad..4a33924 100644 --- a/ec/musig2/bench_test.go +++ b/ec/musig2/bench_test.go @@ -18,7 +18,7 @@ var ( testMsg = hexToBytes("c301ba9de5d6053caad9f5eb46523f007702add2c62fa39de03146a36b8026b7") ) -func hexToBytes(s st) by { +func hexToBytes(s string) []byte { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -26,7 +26,7 @@ func hexToBytes(s st) by { return b } -func hexToModNScalar(s st) *btcec.ModNScalar { +func hexToModNScalar(s string) *btcec.ModNScalar { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -57,16 +57,16 @@ func genSigner(t *testing.B) signer { var ( testSig *PartialSignature - testErr er + testErr error ) // BenchmarkPartialSign benchmarks how long it takes to generate a partial // signature factoring in if the keys are sorted and also if we're in fast sign // mode. func BenchmarkPartialSign(b *testing.B) { - for _, numSigners := range []no{10, 100} { - for _, fastSign := range []bo{true, false} { - for _, sortKeys := range []bo{true, false} { + for _, numSigners := range []int{10, 100} { + for _, fastSign := range []bool{true, false} { + for _, sortKeys := range []bool{true, false} { name := fmt.Sprintf("num_signers=%v/fast_sign=%v/sort=%v", numSigners, fastSign, sortKeys) signers := make(signerSet, numSigners) @@ -176,7 +176,7 @@ var finalSchnorrSig *schnorr.Signature // BenchmarkCombineSigs benchmarks how long it takes to combine a set amount of // signatures. func BenchmarkCombineSigs(b *testing.B) { - for _, numSigners := range []no{10, 100} { + for _, numSigners := range []int{10, 100} { signers := make(signerSet, numSigners) for i := 0; i < numSigners; i++ { signers[i] = genSigner(b) @@ -218,7 +218,7 @@ var testNonce [PubNonceSize]byte // BenchmarkAggregateNonces benchmarks how long it takes to combine nonces. func BenchmarkAggregateNonces(b *testing.B) { - for _, numSigners := range []no{10, 100} { + for _, numSigners := range []int{10, 100} { signers := make(signerSet, numSigners) for i := 0; i < numSigners; i++ { signers[i] = genSigner(b) @@ -242,8 +242,8 @@ var testKey *btcec.PublicKey // BenchmarkAggregateKeys benchmarks how long it takes to aggregate public // keys. func BenchmarkAggregateKeys(b *testing.B) { - for _, numSigners := range []no{10, 100} { - for _, sortKeys := range []bo{true, false} { + for _, numSigners := range []int{10, 100} { + for _, sortKeys := range []bool{true, false} { signers := make(signerSet, numSigners) for i := 0; i < numSigners; i++ { signers[i] = genSigner(b) diff --git a/ec/musig2/context.go b/ec/musig2/context.go index c715868..2b6d4ec 100644 --- a/ec/musig2/context.go +++ b/ec/musig2/context.go @@ -64,14 +64,14 @@ type Context struct { combinedKey *AggregateKey // uniqueKeyIndex is the index of the second unique key in the keySet. // This is used to speed up signing and verification computations. - uniqueKeyIndex no + uniqueKeyIndex int // keysHash is the hash of all the keys as defined in musig2. - keysHash by + keysHash []byte // opts is the set of options for the context. opts *contextOptions // shouldSort keeps track of if the public keys should be sorted before // any operations. - shouldSort bo + shouldSort bool // sessionNonce will be populated if the earlyNonce option is true. // After the first session is created, this nonce will be blanked out. sessionNonce *Nonces @@ -94,18 +94,18 @@ type contextOptions struct { // use it as the internal key. This is required as the taproot tweak // also commits to the public key, which in this case is the aggregated // key before the tweak. - taprootTweak by + taprootTweak []byte // bip86Tweak if true, then the weak will just be // h_tapTweak(internalKey) as there is no true script root. - bip86Tweak bo + bip86Tweak bool // keySet is the complete set of signers for this context. keySet []*btcec.PublicKey // numSigners is the total number of signers that will eventually be a // part of the context. - numSigners no + numSigners int // earlyNonce determines if a nonce should be generated during context // creation, to be automatically passed to the created session. - earlyNonce bo + earlyNonce bool } // defaultContextOptions returns the default context options. @@ -121,7 +121,7 @@ func WithTweakedContext(tweaks ...KeyTweakDesc) ContextOption { // use the taproot tweak as defined in BIP 341: outputKey = internalKey + // h_tapTweak(internalKey || scriptRoot). In this case, the aggreaged key // before the tweak will be used as the internal key. -func WithTaprootTweakCtx(scriptRoot by) ContextOption { +func WithTaprootTweakCtx(scriptRoot []byte) ContextOption { return func(o *contextOptions) { o.taprootTweak = scriptRoot } } @@ -148,7 +148,7 @@ func WithKnownSigners(signers []*btcec.PublicKey) ContextOption { // the signers are known. // // NOTE: Either WithKnownSigners or WithNumSigners MUST be specified. -func WithNumSigners(n no) ContextOption { +func WithNumSigners(n int) ContextOption { return func(o *contextOptions) { o.numSigners = n } } @@ -165,8 +165,8 @@ func WithEarlyNonceGen() ContextOption { // of public keys for each of the other signers. // // NOTE: This struct should be used over the raw Sign API whenever possible. -func NewContext(signingKey *btcec.SecretKey, shouldSort bo, - ctxOpts ...ContextOption) (*Context, er) { +func NewContext(signingKey *btcec.SecretKey, shouldSort bool, + ctxOpts ...ContextOption) (*Context, error) { // First, parse the set of optional context options. opts := defaultContextOptions() @@ -202,7 +202,7 @@ func NewContext(signingKey *btcec.SecretKey, shouldSort bo, // If early nonce generation is specified, then we'll generate the // nonce now to pass in to the session once all the callers are known. if opts.earlyNonce { - var err er + var err error ctx.sessionNonce, err = GenNonces( WithPublicKey(ctx.pubKey), WithNonceSecretKeyAux(signingKey), @@ -216,10 +216,10 @@ func NewContext(signingKey *btcec.SecretKey, shouldSort bo, // combineSignerKeys is used to compute the aggregated signer key once all the // signers are known. -func (c *Context) combineSignerKeys() er { +func (c *Context) combineSignerKeys() error { // As a sanity check, make sure the signing key is actually // amongst the sit of signers. - var keyFound bo + var keyFound bool for _, key := range c.opts.keySet { if key.IsEqual(c.pubKey) { keyFound = true @@ -255,7 +255,7 @@ func (c *Context) combineSignerKeys() er { } // Next, we'll use this information to compute the aggregated // public key that'll be used for signing in practice. - var err er + var err error c.combinedKey, _, _, err = AggregateKeys( c.opts.keySet, c.shouldSort, keyAggOpts..., ) @@ -266,7 +266,7 @@ func (c *Context) combineSignerKeys() er { } // EarlySessionNonce returns the early session nonce, if available. -func (c *Context) EarlySessionNonce() (*Nonces, er) { +func (c *Context) EarlySessionNonce() (*Nonces, error) { if c.sessionNonce == nil { return nil, ErrNoEarlyNonce } @@ -282,7 +282,7 @@ func (c *Context) EarlySessionNonce() (*Nonces, er) { // // NOTE: If the set of keys are not to be sorted during signing, then the // ordering each key is registered with MUST match the desired ordering. -func (c *Context) RegisterSigner(pub *btcec.PublicKey) (bo, er) { +func (c *Context) RegisterSigner(pub *btcec.PublicKey) (bool, error) { haveAllSigners := len(c.opts.keySet) == c.opts.numSigners if haveAllSigners { return false, ErrAlreadyHaveAllSigners @@ -300,11 +300,11 @@ func (c *Context) RegisterSigner(pub *btcec.PublicKey) (bo, er) { } // NumRegisteredSigners returns the total number of registered signers. -func (c *Context) NumRegisteredSigners() no { return len(c.opts.keySet) } +func (c *Context) NumRegisteredSigners() int { return len(c.opts.keySet) } // CombinedKey returns the combined public key that will be used to generate // multi-signatures against. -func (c *Context) CombinedKey() (*btcec.PublicKey, er) { +func (c *Context) CombinedKey() (*btcec.PublicKey, error) { // If the caller hasn't registered all the signers at this point, then // the combined key won't be available. if c.combinedKey == nil { @@ -328,7 +328,7 @@ func (c *Context) SigningKeys() []*btcec.PublicKey { // CombinedKey() will return the fully tweaked output key, with this method // returning the internal key. If a taproot tweak wasn't specified, then this // method will return an error. -func (c *Context) TaprootInternalKey() (*btcec.PublicKey, er) { +func (c *Context) TaprootInternalKey() (*btcec.PublicKey, error) { // If the caller hasn't registered all the signers at this point, then // the combined key won't be available. if c.combinedKey == nil { @@ -380,7 +380,7 @@ type Session struct { } // NewSession creates a new musig2 signing session. -func (c *Context) NewSession(options ...SessionOption) (*Session, er) { +func (c *Context) NewSession(options ...SessionOption) (*Session, error) { opts := defaultSessionOptions() for _, opt := range options { opt(opts) @@ -408,7 +408,7 @@ func (c *Context) NewSession(options ...SessionOption) (*Session, er) { } // Now that we know we have enough signers, we'll either use the caller // specified nonce, or generate a fresh set. - var err er + var err error if localNonces == nil { // At this point we need to generate a fresh nonce. We'll pass // in some auxiliary information to strengthen the nonce @@ -442,12 +442,12 @@ func (s *Session) PublicNonce() [PubNonceSize]byte { // NumRegisteredNonces returns the total number of nonces that have been // regsitered so far. -func (s *Session) NumRegisteredNonces() no { return len(s.pubNonces) } +func (s *Session) NumRegisteredNonces() int { return len(s.pubNonces) } // RegisterPubNonce should be called for each public nonce from the set of // signers. This method returns true once all the public nonces have been // accounted for. -func (s *Session) RegisterPubNonce(nonce [PubNonceSize]byte) (bo, er) { +func (s *Session) RegisterPubNonce(nonce [PubNonceSize]byte) (bool, error) { // If we already have all the nonces, then this method was called too // many times. haveAllNonces := len(s.pubNonces) == s.ctx.opts.numSigners @@ -474,7 +474,7 @@ func (s *Session) RegisterPubNonce(nonce [PubNonceSize]byte) (bo, er) { // context. If this method is called more than once per context, then an error // is returned, as that means a nonce was re-used. func (s *Session) Sign(msg [32]byte, - signOpts ...SignOption) (*PartialSignature, er) { + signOpts ...SignOption) (*PartialSignature, error) { switch { // If no local nonce is present, then this means we already signed, so @@ -517,7 +517,7 @@ func (s *Session) Sign(msg [32]byte, // CombineSig buffers a partial signature received from a signing party. The // method returns true once all the signatures are available, and can be // combined into the final signature. -func (s *Session) CombineSig(sig *PartialSignature) (bo, er) { +func (s *Session) CombineSig(sig *PartialSignature) (bool, error) { // First check if we already have all the signatures we need. We // already accumulated our own signature when we generated the sig. haveAllSigs := len(s.sigs) == len(s.ctx.opts.keySet) diff --git a/ec/musig2/keys.go b/ec/musig2/keys.go index a075dcc..1e728b5 100644 --- a/ec/musig2/keys.go +++ b/ec/musig2/keys.go @@ -16,10 +16,10 @@ import ( var ( // KeyAggTagList is the tagged hash tag used to compute the hash of the // list of sorted public keys. - KeyAggTagList = by("KeyAgg list") + KeyAggTagList = []byte("KeyAgg list") // KeyAggTagCoeff is the tagged hash tag used to compute the key // aggregation coefficient for each key. - KeyAggTagCoeff = by("KeyAgg coefficient") + KeyAggTagCoeff = []byte("KeyAgg coefficient") // ErrTweakedKeyIsInfinity is returned if while tweaking a key, we end // up with the point at infinity. ErrTweakedKeyIsInfinity = fmt.Errorf("tweaked key is infinity point") @@ -34,7 +34,7 @@ type sortableKeys []*btcec.PublicKey // Less reports whether the element with index i must sort before the element // with index j. -func (s sortableKeys) Less(i, j no) bo { +func (s sortableKeys) Less(i, j int) bool { // TODO(roasbeef): more efficient way to compare... keyIBytes := s[i].SerializeCompressed() keyJBytes := s[j].SerializeCompressed() @@ -42,10 +42,10 @@ func (s sortableKeys) Less(i, j no) bo { } // Swap swaps the elements with indexes i and j. -func (s sortableKeys) Swap(i, j no) { s[i], s[j] = s[j], s[i] } +func (s sortableKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Len is the number of elements in the collection. -func (s sortableKeys) Len() no { return len(s) } +func (s sortableKeys) Len() int { return len(s) } // sortKeys takes a set of public keys and returns a new slice that is a copy // of the keys sorted in lexicographical order bytes on the x-only pubkey @@ -63,13 +63,13 @@ func sortKeys(keys []*btcec.PublicKey) []*btcec.PublicKey { // keys passed as input. This is used to compute the aggregation coefficient // for each key. The final computation is: // - H(tag=KeyAgg list, pk1 || pk2..) -func keyHashFingerprint(keys []*btcec.PublicKey, sort bo) by { +func keyHashFingerprint(keys []*btcec.PublicKey, sort bool) []byte { if sort { keys = sortKeys(keys) } // We'll create a single buffer and slice into that so the bytes buffer // doesn't continually need to grow the underlying buffer. - keyAggBuf := make(by, 33*len(keys)) + keyAggBuf := make([]byte, 33*len(keys)) keyBytes := bytes.NewBuffer(keyAggBuf[0:0]) for _, key := range keys { keyBytes.Write(key.SerializeCompressed()) @@ -80,16 +80,16 @@ func keyHashFingerprint(keys []*btcec.PublicKey, sort bo) by { // keyBytesEqual returns true if two keys are the same based on the compressed // serialization of each key. -func keyBytesEqual(a, b *btcec.PublicKey) bo { - return equals(a.SerializeCompressed(), b.SerializeCompressed()) +func keyBytesEqual(a, b *btcec.PublicKey) bool { + return bytes.Equal(a.SerializeCompressed(), b.SerializeCompressed()) } // aggregationCoefficient computes the key aggregation coefficient for the // specified target key. The coefficient is computed as: // - H(tag=KeyAgg coefficient, keyHashFingerprint(pks) || pk) func aggregationCoefficient(keySet []*btcec.PublicKey, - targetKey *btcec.PublicKey, keysHash by, - secondKeyIdx no) *btcec.ModNScalar { + targetKey *btcec.PublicKey, keysHash []byte, + secondKeyIdx int) *btcec.ModNScalar { var mu btcec.ModNScalar // If this is the second key, then this coefficient is just one. @@ -109,7 +109,7 @@ func aggregationCoefficient(keySet []*btcec.PublicKey, // secondUniqueKeyIndex returns the index of the second unique key. If all keys // are the same, then a value of -1 is returned. -func secondUniqueKeyIndex(keySet []*btcec.PublicKey, sort bo) no { +func secondUniqueKeyIndex(keySet []*btcec.PublicKey, sort bool) int { if sort { keySet = sortKeys(keySet) } @@ -134,7 +134,7 @@ type KeyTweakDesc struct { Tweak [32]byte // IsXOnly if true, then the public key will be mapped to an x-only key // before the tweaking operation is applied. - IsXOnly bo + IsXOnly bool } // KeyAggOption is a functional option argument that allows callers to specify @@ -145,30 +145,30 @@ type KeyAggOption func(*keyAggOption) // aggregation. type keyAggOption struct { // keyHash is the output of keyHashFingerprint for a given set of keys. - keyHash by + keyHash []byte // uniqueKeyIndex is the pre-computed index of the second unique key. - uniqueKeyIndex *no + uniqueKeyIndex *int // tweaks specifies a series of tweaks to be applied to the aggregated // public key. tweaks []KeyTweakDesc // taprootTweak controls if the tweaks above should be applied in a BIP // 340 style. - taprootTweak bo + taprootTweak bool // bip86Tweak specifies that the taproot tweak should be done in a BIP // 86 style, where we don't expect an actual tweak and instead just // commit to the public key itself. - bip86Tweak bo + bip86Tweak bool } // WithKeysHash allows key aggregation to be optimize, by allowing the caller // to specify the hash of all the keys. -func WithKeysHash(keyHash by) KeyAggOption { +func WithKeysHash(keyHash []byte) KeyAggOption { return func(o *keyAggOption) { o.keyHash = keyHash } } // WithUniqueKeyIndex allows the caller to specify the index of the second // unique key. -func WithUniqueKeyIndex(idx no) KeyAggOption { +func WithUniqueKeyIndex(idx int) KeyAggOption { return func(o *keyAggOption) { i := idx o.uniqueKeyIndex = &i @@ -189,7 +189,7 @@ func WithKeyTweaks(tweaks ...KeyTweakDesc) KeyAggOption { // This option should be used instead of WithKeyTweaks when the aggregated key // is intended to be used as a taproot output key that commits to a script // root. -func WithTaprootKeyTweak(scriptRoot by) KeyAggOption { +func WithTaprootKeyTweak(scriptRoot []byte) KeyAggOption { return func(o *keyAggOption) { var tweak [32]byte copy(tweak[:], scriptRoot[:]) @@ -223,7 +223,7 @@ func defaultKeyAggOptions() *keyAggOption { return &keyAggOption{} } // point has an even y coordinate. // // TODO(roasbeef): double check, can just check the y coord even not jacobian? -func hasEvenY(pJ btcec.JacobianPoint) bo { +func hasEvenY(pJ btcec.JacobianPoint) bool { pJ.ToAffine() p := btcec.NewPublicKey(&pJ.X, &pJ.Y) keyBytes := p.SerializeCompressed() @@ -238,7 +238,7 @@ func hasEvenY(pJ btcec.JacobianPoint) bo { func tweakKey(keyJ btcec.JacobianPoint, parityAcc btcec.ModNScalar, tweak [32]byte, tweakAcc btcec.ModNScalar, - xOnly bo) (btcec.JacobianPoint, btcec.ModNScalar, btcec.ModNScalar, er) { + xOnly bool) (btcec.JacobianPoint, btcec.ModNScalar, btcec.ModNScalar, error) { // First we'll compute the new parity factor for this key. If the key has // an odd y coordinate (not even), then we'll need to negate it (multiply @@ -298,9 +298,9 @@ type AggregateKey struct { // value can be passed for keyHash, which causes this function to re-derive it. // In addition to the combined public key, the parity accumulator and the tweak // accumulator are returned as well. -func AggregateKeys(keys []*btcec.PublicKey, sort bo, +func AggregateKeys(keys []*btcec.PublicKey, sort bool, keyOpts ...KeyAggOption) ( - *AggregateKey, *btcec.ModNScalar, *btcec.ModNScalar, er) { + *AggregateKey, *btcec.ModNScalar, *btcec.ModNScalar, error) { // First, parse the set of optional signing options. opts := defaultKeyAggOptions() for _, option := range keyOpts { @@ -361,7 +361,7 @@ func AggregateKeys(keys []*btcec.PublicKey, sort bo, // to a BIP-0086 key only spend output. Otherwise, we just // commit to the internal key and an empty byte slice as the // root hash. - tweakBytes := by{} + tweakBytes := []byte{} if !opts.bip86Tweak { tweakBytes = opts.tweaks[0].Tweak[:] } @@ -377,7 +377,7 @@ func AggregateKeys(keys []*btcec.PublicKey, sort bo, } var ( - err er + err error tweakAcc btcec.ModNScalar parityAcc btcec.ModNScalar ) diff --git a/ec/musig2/keys_test.go b/ec/musig2/keys_test.go index 4271464..080ba84 100644 --- a/ec/musig2/keys_test.go +++ b/ec/musig2/keys_test.go @@ -25,8 +25,8 @@ const ( ) type keySortTestVector struct { - PubKeys []st `json:"pubkeys"` - SortedKeys []st `json:"sorted_pubkeys"` + PubKeys []string `json:"pubkeys"` + SortedKeys []string `json:"sorted_pubkeys"` } // TestMusig2KeySort tests that keys are properly sorted according to the @@ -57,36 +57,36 @@ func TestMusig2KeySort(t *testing.T) { } type keyAggValidTest struct { - Indices []no `json:"key_indices"` - Expected st `json:"expected"` + Indices []int `json:"key_indices"` + Expected string `json:"expected"` } type keyAggError struct { - Type st `json:"type"` - Signer no `json:"signer"` - Contring st `json:"contrib"` + Type string `json:"type"` + Signer int `json:"signer"` + Contring string `json:"contrib"` } type keyAggInvalidTest struct { - Indices []no `json:"key_indices"` - TweakIndices []no `json:"tweak_indices"` - IsXOnly []bo `json:"is_xonly"` - Comment st `json:"comment"` + Indices []int `json:"key_indices"` + TweakIndices []int `json:"tweak_indices"` + IsXOnly []bool `json:"is_xonly"` + Comment string `json:"comment"` } type keyAggTestVectors struct { - PubKeys []st `json:"pubkeys"` - Tweaks []st `json:"tweaks"` + PubKeys []string `json:"pubkeys"` + Tweaks []string `json:"tweaks"` ValidCases []keyAggValidTest `json:"valid_test_cases"` InvalidCases []keyAggInvalidTest `json:"error_test_cases"` } -func keysFromIndices(t *testing.T, indices []no, - pubKeys []st) ([]*btcec.PublicKey, er) { +func keysFromIndices(t *testing.T, indices []int, + pubKeys []string) ([]*btcec.PublicKey, error) { t.Helper() inputKeys := make([]*btcec.PublicKey, len(indices)) for i, keyIdx := range indices { - var err er + var err error inputKeys[i], err = btcec.ParsePubKey( mustParseHex(pubKeys[keyIdx]), ) @@ -97,8 +97,8 @@ func keysFromIndices(t *testing.T, indices []no, return inputKeys, nil } -func tweaksFromIndices(t *testing.T, indices []no, - tweaks []st, isXonly []bo) []KeyTweakDesc { +func tweaksFromIndices(t *testing.T, indices []int, + tweaks []string, isXonly []bool) []KeyTweakDesc { t.Helper() testTweaks := make([]KeyTweakDesc, len(indices)) @@ -124,7 +124,7 @@ func TestMuSig2KeyAggTestVectors(t *testing.T) { require.NoError(t, err) var testCases keyAggTestVectors require.NoError(t, json.Unmarshal(testVectorBytes, &testCases)) - tweaks := make([]by, len(testCases.Tweaks)) + tweaks := make([][]byte, len(testCases.Tweaks)) for i := range testCases.Tweaks { tweaks[i] = mustParseHex(testCases.Tweaks[i]) } @@ -217,38 +217,38 @@ func TestMuSig2KeyAggTestVectors(t *testing.T) { } type keyTweakInvalidTest struct { - Indices []no `json:"key_indices"` - NonceIndices []no `json:"nonce_indices"` - TweakIndices []no `json:"tweak_indices"` - IsXOnly []bo `json:"is_only"` - SignerIndex no `json:"signer_index"` - Comment st `json:"comment"` + Indices []int `json:"key_indices"` + NonceIndices []int `json:"nonce_indices"` + TweakIndices []int `json:"tweak_indices"` + IsXOnly []bool `json:"is_only"` + SignerIndex int `json:"signer_index"` + Comment string `json:"comment"` } type keyTweakValidTest struct { - Indices []no `json:"key_indices"` - NonceIndices []no `json:"nonce_indices"` - TweakIndices []no `json:"tweak_indices"` - IsXOnly []bo `json:"is_xonly"` - SignerIndex no `json:"signer_index"` - Expected st `json:"expected"` - Comment st `json:"comment"` + Indices []int `json:"key_indices"` + NonceIndices []int `json:"nonce_indices"` + TweakIndices []int `json:"tweak_indices"` + IsXOnly []bool `json:"is_xonly"` + SignerIndex int `json:"signer_index"` + Expected string `json:"expected"` + Comment string `json:"comment"` } type keyTweakVector struct { - SecKey st `json:"sk"` - PubKeys []st `json:"pubkeys"` - PrivNonce st `json:"secnonce"` - PubNonces []st `json:"pnonces"` - AggNnoce st `json:"aggnonce"` - Tweaks []st `json:"tweaks"` - Msg st `json:"msg"` + SecKey string `json:"sk"` + PubKeys []string `json:"pubkeys"` + PrivNonce string `json:"secnonce"` + PubNonces []string `json:"pnonces"` + AggNnoce string `json:"aggnonce"` + Tweaks []string `json:"tweaks"` + Msg string `json:"msg"` ValidCases []keyTweakValidTest `json:"valid_test_cases"` InvalidCases []keyTweakInvalidTest `json:"error_test_cases"` } -func pubNoncesFromIndices(t *testing.T, nonceIndices []no, - pubNonces []st) [][PubNonceSize]byte { +func pubNoncesFromIndices(t *testing.T, nonceIndices []int, + pubNonces []string) [][PubNonceSize]byte { nonces := make([][PubNonceSize]byte, len(nonceIndices)) for i, idx := range nonceIndices { diff --git a/ec/musig2/musig2_test.go b/ec/musig2/musig2_test.go index 40ae3c6..7608713 100644 --- a/ec/musig2/musig2_test.go +++ b/ec/musig2/musig2_test.go @@ -17,7 +17,7 @@ const ( testVectorBaseDir = "data" ) -func mustParseHex(str st) by { +func mustParseHex(str string) []byte { b, err := hex.Dec(str) if err != nil { panic(fmt.Errorf("unable to parse hex: %v", err)) @@ -67,7 +67,7 @@ func (s signerSet) combinedKey() *btcec.PublicKey { } // testMultiPartySign executes a multi-party signing context w/ 100 signers. -func testMultiPartySign(t *testing.T, taprootTweak by, +func testMultiPartySign(t *testing.T, taprootTweak []byte, tweaks ...KeyTweakDesc) { const numSigners = 100 @@ -123,7 +123,7 @@ func testMultiPartySign(t *testing.T, taprootTweak by, for i, signCtx := range signers { signCtx := signCtx wg.Add(1) - go func(idx no, signer *Session) { + go func(idx int, signer *Session) { defer wg.Done() for j, otherCtx := range signers { if idx == j { @@ -141,7 +141,7 @@ func testMultiPartySign(t *testing.T, taprootTweak by, }(i, signCtx) } wg.Wait() - msg := sha256.Sum256(by("let's get taprooty")) + msg := sha256.Sum256([]byte("let's get taprooty")) // In the final step, we'll use the first signer as our combiner, and // generate a signature for each signer, and then accumulate that with // the combiner. @@ -221,7 +221,7 @@ func TestMuSigMultiParty(t *testing.T) { t.Run("taproot_bip_86", func(t *testing.T) { t.Parallel() - testMultiPartySign(t, by{}) + testMultiPartySign(t, []byte{}) }) } @@ -317,7 +317,7 @@ func TestMuSigEarlyNonce(t *testing.T) { if err != nil { t.Fatalf("unable to create new session: %v", err) } - msg := sha256.Sum256(by("let's get taprooty, LN style")) + msg := sha256.Sum256([]byte("let's get taprooty, LN style")) // If we try to sign before we have the combined nonce, we shoudl get // an error. _, err = session1.Sign(msg) @@ -378,10 +378,10 @@ func TestMuSigEarlyNonce(t *testing.T) { } type memsetRandReader struct { - i no + i int } -func (mr *memsetRandReader) Read(buf by) (n no, err er) { +func (mr *memsetRandReader) Read(buf []byte) (n int, err error) { for i := range buf { buf[i] = byte(mr.i) } diff --git a/ec/musig2/nonces.go b/ec/musig2/nonces.go index 0bc4810..d9084cd 100644 --- a/ec/musig2/nonces.go +++ b/ec/musig2/nonces.go @@ -27,10 +27,10 @@ const ( var ( // NonceAuxTag is the tag used to optionally mix in the secret key with // the set of aux randomness. - NonceAuxTag = by("MuSig/aux") + NonceAuxTag = []byte("MuSig/aux") // NonceGenTag is used to generate the value (from a set of required an // optional field) that will be used as the part of the secret nonce. - NonceGenTag = by("MuSig/nonce") + NonceGenTag = []byte("MuSig/nonce") byteOrder = binary.BigEndian // ErrPubkeyInvalid is returned when the pubkey of the WithPublicKey // option is not passed or of invalid length. @@ -92,19 +92,19 @@ type nonceGenOpts struct { randReader io.Reader // publicKey is the mandatory public key that will be mixed into the nonce // generation. - publicKey by + publicKey []byte // secretKey is an optional argument that's used to further augment the // generated nonce by xor'ing it with this secret key. - secretKey by + secretKey []byte // combinedKey is an optional argument that if specified, will be // combined along with the nonce generation. - combinedKey by + combinedKey []byte // msg is an optional argument that will be mixed into the nonce // derivation algorithm. - msg by + msg []byte // auxInput is an optional argument that will be mixed into the nonce // derivation algorithm. - auxInput by + auxInput []byte } // cryptoRandAdapter is an adapter struct that allows us to pass in the package @@ -115,7 +115,7 @@ type cryptoRandAdapter struct{} // Read implements the io.Reader interface for the crypto/rand package. By // default, we always use the crypto/rand reader, but the caller is able to // specify their own generation, which can be useful for deterministic tests. -func (c *cryptoRandAdapter) Read(p by) (n no, err er) { +func (c *cryptoRandAdapter) Read(p []byte) (n int, err error) { return rand.Read(p) } @@ -164,7 +164,7 @@ func WithNonceMessageAux(msg [32]byte) NonceGenOption { // WithNonceAuxInput is a set of auxiliary randomness, similar to BIP 340 that // can be used to further augment the nonce generation process. -func WithNonceAuxInput(aux by) NonceGenOption { +func WithNonceAuxInput(aux []byte) NonceGenOption { return func(o *nonceGenOpts) { o.auxInput = aux } } @@ -187,30 +187,30 @@ func withCustomOptions(customOpts nonceGenOpts) NonceGenOption { // length prefix of a byte slice is written. // // TODO(roasbeef): use type params once we bump repo version -type lengthWriter func(w io.Writer, b by) er +type lengthWriter func(w io.Writer, b []byte) error // uint8Writer is an implementation of lengthWriter that writes the length of // the byte slice using 1 byte. -func uint8Writer(w io.Writer, b by) er { +func uint8Writer(w io.Writer, b []byte) error { return binary.Write(w, byteOrder, uint8(len(b))) } // uint32Writer is an implementation of lengthWriter that writes the length of // the byte slice using 4 bytes. -func uint32Writer(w io.Writer, b by) er { +func uint32Writer(w io.Writer, b []byte) error { return binary.Write(w, byteOrder, uint32(len(b))) } // uint32Writer is an implementation of lengthWriter that writes the length of // the byte slice using 8 bytes. -func uint64Writer(w io.Writer, b by) er { +func uint64Writer(w io.Writer, b []byte) error { return binary.Write(w, byteOrder, uint64(len(b))) } // writeBytesPrefix is used to write out: len(b) || b, to the passed io.Writer. // The lengthWriter function closure is used to allow the caller to specify the // precise byte packing of the length. -func writeBytesPrefix(w io.Writer, b by, lenWriter lengthWriter) er { +func writeBytesPrefix(w io.Writer, b []byte, lenWriter lengthWriter) error { // Write out the length of the byte first, followed by the set of bytes // itself. if err := lenWriter(w, b); chk.T(err) { @@ -231,8 +231,8 @@ func writeBytesPrefix(w io.Writer, b by, lenWriter lengthWriter) er { // where i is the ith secret nonce being generated and m_prefixed is: // - bytes(1, 0) if the message is blank // - bytes(1, 1) || bytes(8, len(m)) || m if the message is present. -func genNonceAuxBytes(rand by, pubkey by, i no, - opts *nonceGenOpts) (*chainhash.Hash, er) { +func genNonceAuxBytes(rand []byte, pubkey []byte, i int, + opts *nonceGenOpts) (*chainhash.Hash, error) { var w bytes.Buffer // First, write out the randomness generated in the prior step. @@ -253,7 +253,7 @@ func genNonceAuxBytes(rand by, pubkey by, i no, // If the message isn't present, then we'll just write out a single // uint8 of a zero byte: m_prefixed = bytes(1, 0). case opts.msg == nil: - if _, err := w.Write(by{0x00}); chk.T(err) { + if _, err := w.Write([]byte{0x00}); chk.T(err) { return nil, err } // Otherwise, we'll write a single byte of 0x01 with a 1 byte length @@ -262,7 +262,7 @@ func genNonceAuxBytes(rand by, pubkey by, i no, case len(opts.msg) == 0: fallthrough default: - if _, err := w.Write(by{0x01}); chk.T(err) { + if _, err := w.Write([]byte{0x01}); chk.T(err) { return nil, err } err = writeBytesPrefix(&w, opts.msg, uint64Writer) @@ -288,7 +288,7 @@ func genNonceAuxBytes(rand by, pubkey by, i no, // GenNonces generates the secret nonces, as well as the public nonces which // correspond to an EC point generated using the secret nonce as a secret key. -func GenNonces(options ...NonceGenOption) (*Nonces, er) { +func GenNonces(options ...NonceGenOption) (*Nonces, error) { opts := defaultNonceGenOpts() for _, opt := range options { opt(opts) @@ -341,14 +341,14 @@ func GenNonces(options ...NonceGenOption) (*Nonces, er) { // AggregateNonces aggregates the set of a pair of public nonces for each party // into a single aggregated nonces to be used for multi-signing. func AggregateNonces(pubNonces [][PubNonceSize]byte) ([PubNonceSize]byte, - er) { + error) { // combineNonces is a helper function that aggregates (adds) up a // series of nonces encoded in compressed format. It uses a slicing // function to extra 33 bytes at a time from the packed 2x public // nonces. - type nonceSlicer func([PubNonceSize]byte) by - combineNonces := func(slicer nonceSlicer) (btcec.JacobianPoint, er) { + type nonceSlicer func([PubNonceSize]byte) []byte + combineNonces := func(slicer nonceSlicer) (btcec.JacobianPoint, error) { // Convert the set of nonces into jacobian coordinates we can // use to accumulate them all into each other. pubNonceJs := make([]*btcec.JacobianPoint, len(pubNonces)) @@ -377,13 +377,13 @@ func AggregateNonces(pubNonces [][PubNonceSize]byte) ([PubNonceSize]byte, // aggregate the first nonce of all the parties, and the other that // aggregates the second nonce of all the parties. var finalNonce [PubNonceSize]byte - combinedNonce1, err := combineNonces(func(n [PubNonceSize]byte) by { + combinedNonce1, err := combineNonces(func(n [PubNonceSize]byte) []byte { return n[:btcec.PubKeyBytesLenCompressed] }) if err != nil { return finalNonce, err } - combinedNonce2, err := combineNonces(func(n [PubNonceSize]byte) by { + combinedNonce2, err := combineNonces(func(n [PubNonceSize]byte) []byte { return n[btcec.PubKeyBytesLenCompressed:] }) if err != nil { diff --git a/ec/musig2/nonces_test.go b/ec/musig2/nonces_test.go index 290834b..4513400 100644 --- a/ec/musig2/nonces_test.go +++ b/ec/musig2/nonces_test.go @@ -3,6 +3,7 @@ package musig2 import ( + "bytes" "encoding/json" "fmt" "os" @@ -10,17 +11,18 @@ import ( "testing" "github.com/stretchr/testify/require" + "realy.lol/hex" ) type nonceGenTestCase struct { - Rand st `json:"rand_"` - Sk st `json:"sk"` - AggPk st `json:"aggpk"` - Msg *st `json:"msg"` - ExtraIn st `json:"extra_in"` - Pk st `json:"pk"` - Expected st `json:"expected"` + Rand string `json:"rand_"` + Sk string `json:"sk"` + AggPk string `json:"aggpk"` + Msg *string `json:"msg"` + ExtraIn string `json:"extra_in"` + Pk string `json:"pk"` + Expected string `json:"expected"` } type nonceGenTestCases struct { @@ -61,7 +63,7 @@ func TestMusig2NonceGenTestVectors(t *testing.T) { t.Fatalf("err gen nonce aux bytes %v", err) } expectedBytes, _ := hex.Dec(testCase.Expected) - if !equals(nonce.SecNonce[:], expectedBytes) { + if !bytes.Equal(nonce.SecNonce[:], expectedBytes) { t.Fatalf("nonces don't match: expected %x, got %x", expectedBytes, nonce.SecNonce[:]) } @@ -70,26 +72,26 @@ func TestMusig2NonceGenTestVectors(t *testing.T) { } type nonceAggError struct { - Type st `json:"type"` - Signer no `json:"signer"` - Contrib st `json:"contrib"` + Type string `json:"type"` + Signer int `json:"signer"` + Contrib string `json:"contrib"` } type nonceAggValidCase struct { - Indices []no `json:"pnonce_indices"` - Expected st `json:"expected"` - Comment st `json:"comment"` + Indices []int `json:"pnonce_indices"` + Expected string `json:"expected"` + Comment string `json:"comment"` } type nonceAggInvalidCase struct { - Indices []no `json:"pnonce_indices"` + Indices []int `json:"pnonce_indices"` Error nonceAggError `json:"error"` - Comment st `json:"comment"` - ExpectedErr st `json:"btcec_err"` + Comment string `json:"comment"` + ExpectedErr string `json:"btcec_err"` } type nonceAggTestCases struct { - Nonces []st `json:"pnonces"` + Nonces []string `json:"pnonces"` ValidCases []nonceAggValidCase `json:"valid_test_cases"` InvalidCases []nonceAggInvalidCase `json:"error_test_cases"` } diff --git a/ec/musig2/sign.go b/ec/musig2/sign.go index a843245..67cf15d 100644 --- a/ec/musig2/sign.go +++ b/ec/musig2/sign.go @@ -16,10 +16,10 @@ import ( var ( // NonceBlindTag is that tag used to construct the value b, which // blinds the second public nonce of each party. - NonceBlindTag = by("MuSig/noncecoef") + NonceBlindTag = []byte("MuSig/noncecoef") // ChallengeHashTag is the tag used to construct the challenge hash - ChallengeHashTag = by("BIP0340/challenge") + ChallengeHashTag = []byte("BIP0340/challenge") // ErrNoncePointAtInfinity is returned if during signing, the fully // combined public nonce is the point at infinity. @@ -72,7 +72,7 @@ func NewPartialSignature(s *btcec.ModNScalar, // Encode writes a serialized version of the partial signature to the passed // io.Writer -func (p *PartialSignature) Encode(w io.Writer) er { +func (p *PartialSignature) Encode(w io.Writer) error { var sBytes [32]byte p.S.PutBytes(&sBytes) @@ -84,7 +84,7 @@ func (p *PartialSignature) Encode(w io.Writer) er { } // Decode attempts to parse a serialized PartialSignature stored in the io reader. -func (p *PartialSignature) Decode(r io.Reader) er { +func (p *PartialSignature) Decode(r io.Reader) error { p.S = new(btcec.ModNScalar) var sBytes [32]byte @@ -109,11 +109,11 @@ type SignOption func(*signOptions) type signOptions struct { // fastSign determines if we'll skip the check at the end of the // routine where we attempt to verify the produced signature. - fastSign bo + fastSign bool // sortKeys determines if the set of keys should be sorted before doing // key aggregation. - sortKeys bo + sortKeys bool // tweaks specifies a series of tweaks to be applied to the aggregated // public key, which also partially carries over into the signing @@ -126,12 +126,12 @@ type signOptions struct { // tweaking, and then use it as the internal key. This is required as // the taproot tweak also commits to the public key, which in this case // is the aggregated key before the tweak. - taprootTweak by + taprootTweak []byte // bip86Tweak specifies that the taproot tweak should be done in a BIP // 86 style, where we don't expect an actual tweak and instead just // commit to the public key itself. - bip86Tweak bo + bip86Tweak bool } // defaultSignOptions returns the default set of signing operations. @@ -173,7 +173,7 @@ func WithTweaks(tweaks ...KeyTweakDesc) SignOption { // This option should be used in the taproot context to create a valid // signature for the keypath spend for taproot, when the output key is actually // committing to a script path, or some other data. -func WithTaprootSignTweak(scriptRoot by) SignOption { +func WithTaprootSignTweak(scriptRoot []byte) SignOption { return func(o *signOptions) { o.taprootTweak = scriptRoot } @@ -197,7 +197,7 @@ func WithBip86SignTweak() SignOption { // be the R value used in the final signature. func computeSigningNonce(combinedNonce [PubNonceSize]byte, combinedKey *btcec.PublicKey, msg [32]byte) ( - *btcec.JacobianPoint, *btcec.ModNScalar, er) { + *btcec.JacobianPoint, *btcec.ModNScalar, error) { // Next we'll compute the value b, that blinds our second public // nonce: @@ -251,7 +251,7 @@ func computeSigningNonce(combinedNonce [PubNonceSize]byte, // infinity. func Sign(secNonce [SecNonceSize]byte, privKey *btcec.SecretKey, combinedNonce [PubNonceSize]byte, pubKeys []*btcec.PublicKey, - msg [32]byte, signOpts ...SignOption) (*PartialSignature, er) { + msg [32]byte, signOpts ...SignOption) (*PartialSignature, error) { // First, parse the set of optional signing options. opts := defaultSignOptions() @@ -260,14 +260,14 @@ func Sign(secNonce [SecNonceSize]byte, privKey *btcec.SecretKey, } // Check that our signing key belongs to the secNonce - if !equals(secNonce[btcec.SecKeyBytesLen*2:], + if !bytes.Equal(secNonce[btcec.SecKeyBytesLen*2:], privKey.PubKey().SerializeCompressed()) { return nil, ErrSecNoncePubkey } // Check that the key set contains the public key to our secret key. - var containsSecKey bo + var containsSecKey bool for _, pk := range pubKeys { if privKey.PubKey().IsEqual(pk) { containsSecKey = true @@ -345,7 +345,7 @@ func Sign(secNonce [SecNonceSize]byte, privKey *btcec.SecretKey, } pubKey := privKey.PubKey() - combinedKeyYIsOdd := func() bo { + combinedKeyYIsOdd := func() bool { combinedKeyBytes := combinedKey.FinalKey.SerializeCompressed() return combinedKeyBytes[0] == secp256k1.PubKeyFormatCompressedOdd }() @@ -407,7 +407,7 @@ func Sign(secNonce [SecNonceSize]byte, privKey *btcec.SecretKey, // signed. func (p *PartialSignature) Verify(pubNonce [PubNonceSize]byte, combinedNonce [PubNonceSize]byte, keySet []*btcec.PublicKey, - signingKey *btcec.PublicKey, msg [32]byte, signOpts ...SignOption) bo { + signingKey *btcec.PublicKey, msg [32]byte, signOpts ...SignOption) bool { pubKey := signingKey.SerializeCompressed() @@ -421,7 +421,7 @@ func (p *PartialSignature) Verify(pubNonce [PubNonceSize]byte, // detailed errors. signed. func verifyPartialSig(partialSig *PartialSignature, pubNonce [PubNonceSize]byte, combinedNonce [PubNonceSize]byte, keySet []*btcec.PublicKey, - pubKey by, msg [32]byte, signOpts ...SignOption) er { + pubKey []byte, msg [32]byte, signOpts ...SignOption) error { opts := defaultSignOptions() for _, option := range signOpts { @@ -617,7 +617,7 @@ func defaultCombineOptions() *combineOptions { // enough information to reconstruct the challenge, and also the final // accumulated tweak value. func WithTweakedCombine(msg [32]byte, keys []*btcec.PublicKey, - tweaks []KeyTweakDesc, sort bo) CombineOption { + tweaks []KeyTweakDesc, sort bool) CombineOption { return func(o *combineOptions) { combinedKey, _, tweakAcc, _ := AggregateKeys( @@ -638,7 +638,7 @@ func WithTweakedCombine(msg [32]byte, keys []*btcec.PublicKey, // aggregate signatures for a top-level taproot keyspend, where the output key // commits to a script root. func WithTaprootTweakedCombine(msg [32]byte, keys []*btcec.PublicKey, - scriptRoot by, sort bo) CombineOption { + scriptRoot []byte, sort bool) CombineOption { return func(o *combineOptions) { combinedKey, _, tweakAcc, _ := AggregateKeys( @@ -660,7 +660,7 @@ func WithTaprootTweakedCombine(msg [32]byte, keys []*btcec.PublicKey, // aggregate signatures for a top-level taproot keyspend, where the output key // was generated using BIP 86. func WithBip86TweakedCombine(msg [32]byte, keys []*btcec.PublicKey, - sort bo) CombineOption { + sort bool) CombineOption { return func(o *combineOptions) { combinedKey, _, tweakAcc, _ := AggregateKeys( diff --git a/ec/musig2/sign_test.go b/ec/musig2/sign_test.go index 971ce1a..aad3832 100644 --- a/ec/musig2/sign_test.go +++ b/ec/musig2/sign_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "realy.lol/ec" "realy.lol/ec/secp256k1" "realy.lol/hex" @@ -23,47 +24,47 @@ const ( ) type signVerifyValidCase struct { - Indices []no `json:"key_indices"` - NonceIndices []no `json:"nonce_indices"` - AggNonceIndex no `json:"aggnonce_index"` - MsgIndex no `json:"msg_index"` - SignerIndex no `json:"signer_index"` - Expected st `json:"expected"` + Indices []int `json:"key_indices"` + NonceIndices []int `json:"nonce_indices"` + AggNonceIndex int `json:"aggnonce_index"` + MsgIndex int `json:"msg_index"` + SignerIndex int `json:"signer_index"` + Expected string `json:"expected"` } type signErrorCase struct { - Indices []no `json:"key_indices"` - AggNonceIndex no `json:"aggnonce_index"` - MsgIndex no `json:"msg_index"` - SecNonceIndex no `json:"secnonce_index"` - Comment st `json:"comment"` + Indices []int `json:"key_indices"` + AggNonceIndex int `json:"aggnonce_index"` + MsgIndex int `json:"msg_index"` + SecNonceIndex int `json:"secnonce_index"` + Comment string `json:"comment"` } type verifyFailCase struct { - Sig st `json:"sig"` - Indices []no `json:"key_indices"` - NonceIndices []no `json:"nonce_indices"` - MsgIndex no `json:"msg_index"` - SignerIndex no `json:"signer_index"` - Comment st `json:"comment"` + Sig string `json:"sig"` + Indices []int `json:"key_indices"` + NonceIndices []int `json:"nonce_indices"` + MsgIndex int `json:"msg_index"` + SignerIndex int `json:"signer_index"` + Comment string `json:"comment"` } type verifyErrorCase struct { - Sig st `json:"sig"` - Indices []no `json:"key_indices"` - NonceIndices []no `json:"nonce_indices"` - MsgIndex no `json:"msg_index"` - SignerIndex no `json:"signer_index"` - Comment st `json:"comment"` + Sig string `json:"sig"` + Indices []int `json:"key_indices"` + NonceIndices []int `json:"nonce_indices"` + MsgIndex int `json:"msg_index"` + SignerIndex int `json:"signer_index"` + Comment string `json:"comment"` } type signVerifyTestVectors struct { - SecKey st `json:"sk"` - PubKeys []st `json:"pubkeys"` - PrivNonces []st `json:"secnonces"` - PubNonces []st `json:"pnonces"` - AggNonces []st `json:"aggnonces"` - Msgs []st `json:"msgs"` + SecKey string `json:"sk"` + PubKeys []string `json:"pubkeys"` + PrivNonces []string `json:"secnonces"` + PubNonces []string `json:"pnonces"` + AggNonces []string `json:"aggnonces"` + Msgs []string `json:"msgs"` ValidCases []signVerifyValidCase `json:"valid_test_cases"` SignErrorCases []signErrorCase `json:"sign_error_test_cases"` VerifyFailCases []verifyFailCase `json:"verify_fail_test_cases"` @@ -211,26 +212,26 @@ func TestMusig2SignVerify(t *testing.T) { } type sigCombineValidCase struct { - AggNonce st `json:"aggnonce"` - NonceIndices []no `json:"nonce_indices"` - Indices []no `json:"key_indices"` - TweakIndices []no `json:"tweak_indices"` - IsXOnly []bo `json:"is_xonly"` - PSigIndices []no `json:"psig_indices"` - Expected st `json:"expected"` + AggNonce string `json:"aggnonce"` + NonceIndices []int `json:"nonce_indices"` + Indices []int `json:"key_indices"` + TweakIndices []int `json:"tweak_indices"` + IsXOnly []bool `json:"is_xonly"` + PSigIndices []int `json:"psig_indices"` + Expected string `json:"expected"` } type sigCombineTestVectors struct { - PubKeys []st `json:"pubkeys"` - PubNonces []st `json:"pnonces"` - Tweaks []st `json:"tweaks"` - Psigs []st `json:"psigs"` - Msg st `json:"msg"` + PubKeys []string `json:"pubkeys"` + PubNonces []string `json:"pnonces"` + Tweaks []string `json:"tweaks"` + Psigs []string `json:"psigs"` + Msg string `json:"msg"` ValidCases []sigCombineValidCase `json:"valid_test_cases"` } -func pSigsFromIndicies(t *testing.T, sigs []st, - indices []no) []*PartialSignature { +func pSigsFromIndicies(t *testing.T, sigs []string, + indices []int) []*PartialSignature { pSigs := make([]*PartialSignature, len(indices)) for i, idx := range indices { var pSig PartialSignature diff --git a/ec/musig2/util.go b/ec/musig2/util.go index 8358d8b..111c3ec 100644 --- a/ec/musig2/util.go +++ b/ec/musig2/util.go @@ -1,22 +1,9 @@ package musig2 import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/pubkey.go b/ec/pubkey.go index d5a94d8..3b3124b 100644 --- a/ec/pubkey.go +++ b/ec/pubkey.go @@ -22,7 +22,7 @@ const ( // IsCompressedPubKey returns true the passed serialized public key has // been encoded in compressed format, and false otherwise. -func IsCompressedPubKey(pubKey by) bo { +func IsCompressedPubKey(pubKey []byte) bool { // The public key is only compressed if it is the correct length and // the format (first byte) is one of the compressed pubkey values. return len(pubKey) == PubKeyBytesLenCompressed && @@ -32,7 +32,7 @@ func IsCompressedPubKey(pubKey by) bo { // ParsePubKey parses a public key for a koblitz curve from a bytestring into a // ecdsa.Publickey, verifying that it is valid. It supports compressed, // uncompressed and hybrid signature formats. -func ParsePubKey(pubKeyStr by) (*PublicKey, er) { +func ParsePubKey(pubKeyStr []byte) (*PublicKey, error) { return secp256k1.ParsePubKey(pubKeyStr) } diff --git a/ec/pubkey_test.go b/ec/pubkey_test.go index 0b6dabe..4c2c17f 100644 --- a/ec/pubkey_test.go +++ b/ec/pubkey_test.go @@ -11,10 +11,10 @@ import ( ) type pubKeyTest struct { - name st - key by + name string + key []byte format byte - isValid bo + isValid bool } var pubKeyTests = []pubKeyTest{ @@ -22,7 +22,7 @@ var pubKeyTests = []pubKeyTest{ // 0437cd7f8525ceed2324359c2d0ba26006d92d85 { name: "uncompressed ok", - key: by{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -36,7 +36,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed x changed", - key: by{0x04, 0x15, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x04, 0x15, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -49,7 +49,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed y changed", - key: by{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -62,7 +62,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed claims compressed", - key: by{0x03, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x03, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -75,7 +75,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed as hybrid ok", - key: by{0x07, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x07, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -89,7 +89,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "uncompressed as hybrid wrong", - key: by{0x06, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x06, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xb2, 0xe0, @@ -103,7 +103,7 @@ var pubKeyTests = []pubKeyTest{ // from tx 0b09c51c51ff762f00fb26217269d2a18e77a4fa87d69b3c363ab4df16543f20 { name: "compressed ok (ybit = 0)", - key: by{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + key: []byte{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, @@ -114,7 +114,7 @@ var pubKeyTests = []pubKeyTest{ // from tx fdeb8e72524e8dab0da507ddbaf5f88fe4a933eb10a66bc4745bb0aa11ea393c { name: "compressed ok (ybit = 1)", - key: by{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + key: []byte{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -124,7 +124,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "compressed claims uncompressed (ybit = 0)", - key: by{0x04, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + key: []byte{0x04, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, @@ -133,7 +133,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "compressed claims uncompressed (ybit = 1)", - key: by{0x05, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + key: []byte{0x05, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -142,12 +142,12 @@ var pubKeyTests = []pubKeyTest{ }, { name: "wrong length)", - key: by{0x05}, + key: []byte{0x05}, isValid: false, }, { name: "X == P", - key: by{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + key: []byte{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F, 0xb2, 0xe0, @@ -160,7 +160,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "X > P", - key: by{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + key: []byte{0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFD, 0x2F, 0xb2, 0xe0, @@ -173,7 +173,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "Y == P", - key: by{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xFF, 0xFF, @@ -186,7 +186,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "Y > P", - key: by{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, + key: []byte{0x04, 0x11, 0xdb, 0x93, 0xe1, 0xdc, 0xdb, 0x8a, 0x01, 0x6b, 0x49, 0x84, 0x0f, 0x8c, 0x53, 0xbc, 0x1e, 0xb6, 0x8a, 0x38, 0x2e, 0x97, 0xb1, 0x48, 0x2e, 0xca, 0xd7, 0xb1, 0x48, 0xa6, 0x90, 0x9a, 0x5c, 0xFF, 0xFF, @@ -199,7 +199,7 @@ var pubKeyTests = []pubKeyTest{ }, { name: "hybrid", - key: by{0x06, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, + key: []byte{0x06, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xce, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98, 0x48, 0x3a, @@ -228,7 +228,7 @@ func TestPubKeys(t *testing.T) { test.name) continue } - var pkStr by + var pkStr []byte switch test.format { case pubkeyUncompressed: pkStr = pk.SerializeUncompressed() @@ -248,7 +248,7 @@ func TestPubKeys(t *testing.T) { func TestPublicKeyIsEqual(t *testing.T) { pubKey1, err := ParsePubKey( - by{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, + []byte{0x03, 0x26, 0x89, 0xc7, 0xc2, 0xda, 0xb1, 0x33, 0x09, 0xfb, 0x14, 0x3e, 0x0e, 0x8f, 0xe3, 0x96, 0x34, 0x25, 0x21, 0x88, 0x7e, 0x97, 0x66, 0x90, 0xb6, 0xb4, 0x7f, 0x5b, 0x2a, 0x4b, 0x7d, 0x44, 0x8e, @@ -258,7 +258,7 @@ func TestPublicKeyIsEqual(t *testing.T) { t.Fatalf("failed to parse raw bytes for pubKey1: %v", err) } pubKey2, err := ParsePubKey( - by{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, + []byte{0x02, 0xce, 0x0b, 0x14, 0xfb, 0x84, 0x2b, 0x1b, 0xa5, 0x49, 0xfd, 0xd6, 0x75, 0xc9, 0x80, 0x75, 0xf1, 0x2e, 0x9c, 0x51, 0x0f, 0x8e, 0xf5, 0x2b, 0xd0, 0x21, 0xa9, 0xa1, 0xf4, 0x80, 0x9d, 0x3b, 0x4d, diff --git a/ec/schnorr/bench_test.go b/ec/schnorr/bench_test.go index 81ed933..b1133f3 100644 --- a/ec/schnorr/bench_test.go +++ b/ec/schnorr/bench_test.go @@ -19,7 +19,7 @@ import ( // is an error. This is only provided for the hard-coded constants so errors in // the source code can be detected. It will only (and must only) be called with // hard-coded values. -func hexToBytes(s st) by { +func hexToBytes(s string) []byte { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -31,7 +31,7 @@ func hexToBytes(s st) by { // panic if there is an error. This is only provided for the hard-coded // constants so errors in the source code can be detected. It will only (and // must only) be called with hard-coded values. -func hexToModNScalar(s st) *btcec.ModNScalar { +func hexToModNScalar(s string) *btcec.ModNScalar { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -47,7 +47,7 @@ func hexToModNScalar(s st) *btcec.ModNScalar { // if there is an error. This is only provided for the hard-coded constants so // errors in the source code can be detected. It will only (and must only) be // called with hard-coded values. -func hexToFieldVal(s st) *btcec.FieldVal { +func hexToFieldVal(s string) *btcec.FieldVal { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -63,7 +63,7 @@ func hexToFieldVal(s st) *btcec.FieldVal { // panic is there is an error. This is only provided for the hard-coded // constants so errors in the source code can bet detected. It will only (and // must only) be called for initialization purposes. -func fromHex(s st) *big.Int { +func fromHex(s string) *big.Int { if s == "" { return big.NewInt(0) } @@ -74,7 +74,7 @@ func fromHex(s st) *big.Int { return r } -var testOk bo +var testOk bool // BenchmarkSign benchmarks how long it takes to sign a message. func BenchmarkSign(b *testing.B) { @@ -88,7 +88,7 @@ func BenchmarkSign(b *testing.B) { auxBytes[0] ^= 1 var ( sig *Signature - err er + err error ) b.ReportAllocs() b.ResetTimer() @@ -109,7 +109,7 @@ func BenchmarkSigVerify(b *testing.B) { privKey := secp256k1.NewSecretKey(d) pubKey := privKey.PubKey() // Double sha256 of by{0x01, 0x02, 0x03, 0x04} - msgHash := sha256.Sum256(by("benchmark")) + msgHash := sha256.Sum256([]byte("benchmark")) sig, err := Sign(privKey, msgHash[:]) if err != nil { b.Fatalf("unable to sign: %v", err) @@ -118,7 +118,7 @@ func BenchmarkSigVerify(b *testing.B) { b.Errorf("Signature failed to verify") return } - var ok bo + var ok bool b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -130,7 +130,7 @@ func BenchmarkSigVerify(b *testing.B) { // Used to ensure the compiler doesn't optimize away the benchmark. var ( testSig *Signature - testErr er + testErr error ) // BenchmarkSignRfc6979 benchmarks how long it takes to sign a message. @@ -142,7 +142,7 @@ func BenchmarkSignRfc6979(b *testing.B) { msgHash := hexToBytes("c301ba9de5d6053caad9f5eb46523f007702add2c62fa39de03146a36b8026b7") var ( sig *Signature - err er + err error ) b.ReportAllocs() b.ResetTimer() diff --git a/ec/schnorr/error.go b/ec/schnorr/error.go index c426692..41d1269 100644 --- a/ec/schnorr/error.go +++ b/ec/schnorr/error.go @@ -9,7 +9,7 @@ package schnorr // ErrorKind identifies a kind of error. It has full support for errors.Is // and errors.As, so the caller can directly check against an error kind // when determining the reason for an error. -type ErrorKind st +type ErrorKind string // These constants are used to identify a specific RuleError. const ( @@ -49,23 +49,23 @@ const ( ) // Error satisfies the error interface and prints human-readable errors. -func (err ErrorKind) Error() st { return st(err) } +func (err ErrorKind) Error() string { return string(err) } // Error identifies an error related to a schnorr signature. It has full // support for errors.Is and errors.As, so the caller can ascertain the // specific reason for the error by checking the underlying error. type Error struct { - Err er - Description st + Err error + Description string } // Error satisfies the error interface and prints human-readable errors. -func (err Error) Error() st { return err.Description } +func (err Error) Error() string { return err.Description } // Unwrap returns the underlying wrapped error. -func (err Error) Unwrap() (ee er) { return err.Err } +func (err Error) Unwrap() (ee error) { return err.Err } // signatureError creates an Error given a set of arguments. -func signatureError(kind ErrorKind, desc st) (err er) { +func signatureError(kind ErrorKind, desc string) (err error) { return Error{Err: kind, Description: desc} } diff --git a/ec/schnorr/pubkey.go b/ec/schnorr/pubkey.go index 0430f61..c3c78ea 100644 --- a/ec/schnorr/pubkey.go +++ b/ec/schnorr/pubkey.go @@ -21,7 +21,7 @@ const ( // ParsePubKey parses a public key for a koblitz curve from a bytestring into a // btcec.Publickey, verifying that it is valid. It only supports public keys in // the BIP-340 32-byte format. -func ParsePubKey(pubKeyStr by) (*btcec.PublicKey, er) { +func ParsePubKey(pubKeyStr []byte) (*btcec.PublicKey, error) { if pubKeyStr == nil { err := fmt.Errorf("nil pubkey byte string") return nil, err @@ -42,7 +42,7 @@ func ParsePubKey(pubKeyStr by) (*btcec.PublicKey, er) { // SerializePubKey serializes a public key as specified by BIP 340. Public keys // in this format are 32 bytes in length, and are assumed to have an even y // coordinate. -func SerializePubKey(pub *btcec.PublicKey) by { +func SerializePubKey(pub *btcec.PublicKey) []byte { pBytes := pub.SerializeCompressed() return pBytes[1:] } diff --git a/ec/schnorr/schnorrerror_test.go b/ec/schnorr/schnorrerror_test.go index fef2000..f4cd5e6 100644 --- a/ec/schnorr/schnorrerror_test.go +++ b/ec/schnorr/schnorrerror_test.go @@ -13,7 +13,7 @@ import ( func TestErrorKindStringer(t *testing.T) { tests := []struct { in ErrorKind - want st + want string }{ {ErrInvalidHashLen, "ErrInvalidHashLen"}, {ErrSecretKeyIsZero, "ErrSecretKeyIsZero"}, @@ -40,7 +40,7 @@ func TestErrorKindStringer(t *testing.T) { func TestError(t *testing.T) { tests := []struct { in Error - want st + want string }{{ Error{Description: "some error"}, "some error", @@ -63,9 +63,9 @@ func TestError(t *testing.T) { func TestErrorKindIsAs(t *testing.T) { tests := []struct { name string - err er - target er - wantMatch bo + err error + target error + wantMatch bool wantAs ErrorKind }{{ name: "ErrInvalidHashLen == ErrInvalidHashLen", diff --git a/ec/schnorr/signature.go b/ec/schnorr/signature.go index d618ec1..638508f 100644 --- a/ec/schnorr/signature.go +++ b/ec/schnorr/signature.go @@ -52,7 +52,7 @@ func NewSignature(r *btcec.FieldVal, s *btcec.ModNScalar) *Signature { // // sig[0:32] x coordinate of the point R, encoded as a big-endian uint256 // sig[32:64] s, encoded also as big-endian uint256 -func (sig Signature) Serialize() by { +func (sig Signature) Serialize() []byte { // Total length of returned signature is the length of r and s. var b [SignatureSize]byte sig.r.PutBytesUnchecked(b[0:32]) @@ -65,7 +65,7 @@ func (sig Signature) Serialize() by { // // - The r component must be in the valid range for secp256k1 field elements // - The s component must be in the valid range for secp256k1 scalars -func ParseSignature(sig by) (*Signature, er) { +func ParseSignature(sig []byte) (*Signature, error) { // The signature must be the correct length. sigLen := len(sig) if sigLen < SignatureSize { @@ -96,7 +96,7 @@ func ParseSignature(sig by) (*Signature, er) { // IsEqual compares this Signature instance to the one passed, returning true // if both Signatures are equivalent. A signature is equivalent to another, if // they both have the same scalar value for R and S. -func (sig Signature) IsEqual(otherSig *Signature) bo { +func (sig Signature) IsEqual(otherSig *Signature) bool { return sig.r.Equals(&otherSig.r) && sig.s.Equals(&otherSig.s) } @@ -107,7 +107,7 @@ func (sig Signature) IsEqual(otherSig *Signature) bo { // This differs from the exported Verify method in that it returns a specific // error to support better testing while the exported method simply returns a // bool indicating success or failure. -func schnorrVerify(sig *Signature, hash by, pubKeyBytes by) er { +func schnorrVerify(sig *Signature, hash []byte, pubKeyBytes []byte) error { // The algorithm for producing a BIP-340 signature is described in // README.md and is reproduced here for reference: // @@ -213,7 +213,7 @@ func schnorrVerify(sig *Signature, hash by, pubKeyBytes by) er { // Verify returns whether or not the signature is valid for the provided hash // and secp256k1 public key. -func (sig *Signature) Verify(hash by, pubKey *btcec.PublicKey) bo { +func (sig *Signature) Verify(hash []byte, pubKey *btcec.PublicKey) bool { pubkeyBytes := SerializePubKey(pubKey) return schnorrVerify(sig, hash, pubkeyBytes) == nil } @@ -234,7 +234,7 @@ func zeroArray(a *[scalarSize]byte) { // NOT be 0. Since this is an internal use function, these preconditions MUST // be satisified by the caller. func schnorrSign(privKey, nonce *btcec.ModNScalar, pubKey *btcec.PublicKey, - hash by, opts *signOptions) (*Signature, er) { + hash []byte, opts *signOptions) (*Signature, error) { // The algorithm for producing a BIP-340 signature is described in // README.md and is reproduced here for reference: @@ -330,7 +330,7 @@ type SignOption func(*signOptions) type signOptions struct { // fastSign determines if we'll skip the check at the end of the routine // where we attempt to verify the produced signature. - fastSign bo + fastSign bool // authNonce allows the user to pass in their own nonce information, which // is useful for schemes like mu-sig. authNonce *[32]byte @@ -365,8 +365,8 @@ func CustomNonce(auxData [32]byte) SignOption { // which can expose the signer to constant time attacks. As a result, this // function should not be used in situations where there is the possibility of // someone having EM field/cache/etc access. -func Sign(privKey *btcec.SecretKey, hash by, - signOpts ...SignOption) (*Signature, er) { +func Sign(privKey *btcec.SecretKey, hash []byte, + signOpts ...SignOption) (*Signature, error) { // First, parse the set of optional signing options. opts := defaultSignOptions() for _, option := range signOpts { diff --git a/ec/schnorr/signature_test.go b/ec/schnorr/signature_test.go index 611b2cb..04a5187 100644 --- a/ec/schnorr/signature_test.go +++ b/ec/schnorr/signature_test.go @@ -19,15 +19,15 @@ import ( ) type bip340Test struct { - secretKey st - publicKey st - auxRand st - message st - signature st - verifyResult bo - validPubKey bo - expectErr er - rfc6979 bo + secretKey string + publicKey string + auxRand string + message string + signature string + verifyResult bool + validPubKey bool + expectErr error + rfc6979 bool } var bip340TestVectors = []bip340Test{ @@ -189,7 +189,7 @@ var bip340TestVectors = []bip340Test{ // decodeHex decodes the passed hex string and returns the resulting bytes. It // panics if an error occurs. This is only used in the tests as a helper since // the only way it can fail is if there is an error in the test source code. -func decodeHex(hexStr st) by { +func decodeHex(hexStr string) []byte { b, err := hex.Dec(hexStr) if err != nil { panic("invalid hex string in test source: err " + err.Error() + @@ -281,7 +281,7 @@ func TestSchnorrSignNoMutate(t *testing.T) { t.Parallel() // Assert that given a random secret key and message, we can generate // a signature from that w/o modifying the underlying secret key. - f := func(privBytes, msg [32]byte) bo { + f := func(privBytes, msg [32]byte) bool { privBytesCopy := privBytes privKey, _ := btcec.SecKeyFromBytes(privBytesCopy[:]) // Generate a signature for secret key with our message. diff --git a/ec/schnorr/util.go b/ec/schnorr/util.go index 64603be..78f3312 100644 --- a/ec/schnorr/util.go +++ b/ec/schnorr/util.go @@ -1,22 +1,9 @@ package schnorr import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/seckey.go b/ec/seckey.go index 1bb8b56..8aa54c2 100644 --- a/ec/seckey.go +++ b/ec/seckey.go @@ -20,7 +20,7 @@ type PrivateKey = SecretKey // SecKeyFromBytes returns a secret and public key for `curve' based on the // secret key passed as an argument as a byte slice. -func SecKeyFromBytes(pk by) (*SecretKey, *PublicKey) { +func SecKeyFromBytes(pk []byte) (*SecretKey, *PublicKey) { privKey := secp256k1.SecKeyFromBytes(pk) return privKey, privKey.PubKey() } @@ -28,7 +28,7 @@ func SecKeyFromBytes(pk by) (*SecretKey, *PublicKey) { var PrivKeyFromBytes = SecKeyFromBytes // NewSecretKey is a wrapper for ecdsa.GenerateKey that returns a SecretKey instead of the normal ecdsa.PrivateKey. -func NewSecretKey() (*SecretKey, er) { return secp256k1.GenerateSecretKey() } +func NewSecretKey() (*SecretKey, error) { return secp256k1.GenerateSecretKey() } // NewPrivateKey is a wrapper for ecdsa.GenerateKey that returns a SecretKey instead of the normal ecdsa.PrivateKey. // diff --git a/ec/secp256k1/curve.go b/ec/secp256k1/curve.go index 7de2c90..4a3b39c 100644 --- a/ec/secp256k1/curve.go +++ b/ec/secp256k1/curve.go @@ -48,7 +48,7 @@ func hexToFieldVal(s string) *FieldVal { // constants so errors in the source code can be detected. It will only (and // must only) be called with hard-coded values. func hexToModNScalar(s string) *ModNScalar { - var isNegative bo + var isNegative bool if len(s) > 0 && s[0] == '-' { isNegative = true s = s[1:] @@ -913,11 +913,11 @@ type nafScalar struct { // Pos returns the bytes of the encoded value with bits set in the positions // that represent a signed digit of +1. -func (s *nafScalar) Pos() by { return s.pos[s.start:s.end] } +func (s *nafScalar) Pos() []byte { return s.pos[s.start:s.end] } // Neg returns the bytes of the encoded value with bits set in the positions // that represent a signed digit of -1. -func (s *nafScalar) Neg() by { return s.neg[s.start:s.end] } +func (s *nafScalar) Neg() []byte { return s.neg[s.start:s.end] } // naf takes a positive integer up to a maximum value of 2^256 - 1 and returns // its non-adjacent form (NAF), which is a unique signed-digit representation @@ -936,7 +936,7 @@ func (s *nafScalar) Neg() by { return s.neg[s.start:s.end] } // doubling. This is an excellent tradeoff because subtraction of points has // the same computational complexity as addition of points and point doubling is // faster than both. -func naf(k by) nafScalar { +func naf(k []byte) nafScalar { // Strip leading zero bytes. for len(k) > 0 && k[0] == 0x00 { k = k[1:] @@ -1190,7 +1190,7 @@ func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) { } // isOnCurve returns whether or not the affine point (x,y) is on the curve. -func isOnCurve(fx, fy *FieldVal) bo { +func isOnCurve(fx, fy *FieldVal) bool { // Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7 y2 := new(FieldVal).SquareVal(fy).Normalize() result := new(FieldVal).SquareVal(fx).Mul(fx).AddInt(7).Normalize() @@ -1204,7 +1204,7 @@ func isOnCurve(fx, fy *FieldVal) bo { // // The magnitude of the provided X coordinate field val must be a max of 8 for a // correct result. The resulting Y field val will have a max magnitude of 2. -func DecompressY(x *FieldVal, odd bo, resultY *FieldVal) bo { +func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool { // The curve equation for secp256k1 is: y^2 = x^3 + 7. Thus // y = +-sqrt(x^3 + 7). // diff --git a/ec/secp256k1/curve_test.go b/ec/secp256k1/curve_test.go index eb7c9e2..ebfd480 100644 --- a/ec/secp256k1/curve_test.go +++ b/ec/secp256k1/curve_test.go @@ -25,7 +25,7 @@ var ( // isValidJacobianPoint returns true if the point (x,y,z) is on the secp256k1 // curve or is the point at infinity. -func isValidJacobianPoint(point *JacobianPoint) bo { +func isValidJacobianPoint(point *JacobianPoint) bool { if (point.X.IsZero() && point.Y.IsZero()) || point.Z.IsZero() { return true } @@ -59,7 +59,7 @@ func jacobianPointFromHex(x, y, z string) JacobianPoint { // in affine coordinates, while not having the same coordinates in projective // space, so the two points not being equal doesn't necessarily mean they aren't // actually the same affine point. -func (p *JacobianPoint) IsStrictlyEqual(other *JacobianPoint) bo { +func (p *JacobianPoint) IsStrictlyEqual(other *JacobianPoint) bool { return p.X.Equals(&other.X) && p.Y.Equals(&other.Y) && p.Z.Equals(&other.Z) } @@ -347,7 +347,7 @@ func TestDoubleJacobian(t *testing.T) { // checkNAFEncoding returns an error if the provided positive and negative // portions of an overall NAF encoding do not adhere to the requirements or they // do not sum back to the provided original value. -func checkNAFEncoding(pos, neg by, origValue *big.Int) (err er) { +func checkNAFEncoding(pos, neg []byte, origValue *big.Int) (err error) { // NAF must not have a leading zero byte and the number of negative // bytes must not exceed the positive portion. if len(pos) > 0 && pos[0] == 0 { @@ -594,7 +594,7 @@ func modNBitLen(s *ModNScalar) uint16 { // checkLambdaDecomposition returns an error if the provided decomposed scalars // do not satisfy the required equation or they are not small in magnitude. -func checkLambdaDecomposition(origK, k1, k2 *ModNScalar) (err er) { +func checkLambdaDecomposition(origK, k1, k2 *ModNScalar) (err error) { // Recompose the scalar from the decomposed scalars to ensure they satisfy // the required equation. calcK := new(ModNScalar).Mul2(k2, endoLambda).Add(k1) @@ -740,7 +740,7 @@ func TestScalarMultJacobianRandom(t *testing.T) { }(t, seed) // isSamePoint returns whether the two Jacobian points represent the // same affine point without modifying the provided points. - isSamePoint := func(p1, p2 *JacobianPoint) bo { + isSamePoint := func(p1, p2 *JacobianPoint) bool { var p1Affine, p2Affine JacobianPoint p1Affine.Set(p1) p1Affine.ToAffine() @@ -813,11 +813,11 @@ func TestScalarMultJacobianRandom(t *testing.T) { // cases. func TestDecompressY(t *testing.T) { tests := []struct { - name st // test description - x st // hex encoded x coordinate - valid bo // expected decompress result - wantOddY st // hex encoded expected odd y coordinate - wantEvenY st // hex encoded expected even y coordinate + name string // test description + x string // hex encoded x coordinate + valid bool // expected decompress result + wantOddY string // hex encoded expected odd y coordinate + wantEvenY string // hex encoded expected even y coordinate }{{ name: "x = 0 -- not a point on the curve", x: "0", diff --git a/ec/secp256k1/ecdh.go b/ec/secp256k1/ecdh.go index e7eb120..9e49092 100644 --- a/ec/secp256k1/ecdh.go +++ b/ec/secp256k1/ecdh.go @@ -11,7 +11,7 @@ package secp256k1 // // It is recommended to securely hash the result before using as a cryptographic // key. -func GenerateSharedSecret(seckey *SecretKey, pubkey *PublicKey) by { +func GenerateSharedSecret(seckey *SecretKey, pubkey *PublicKey) []byte { var point, result JacobianPoint pubkey.AsJacobian(&point) ScalarMultNonConst(&seckey.Key, &point, &result) diff --git a/ec/secp256k1/ecdh_test.go b/ec/secp256k1/ecdh_test.go index 418e405..eb40f2b 100644 --- a/ec/secp256k1/ecdh_test.go +++ b/ec/secp256k1/ecdh_test.go @@ -6,6 +6,7 @@ package secp256k1 import ( + "bytes" "testing" ) @@ -24,7 +25,7 @@ func TestGenerateSharedSecret(t *testing.T) { pubKey2 := secKey2.PubKey() secret1 := GenerateSharedSecret(secKey1, pubKey2) secret2 := GenerateSharedSecret(secKey2, pubKey1) - if !equals(secret1, secret2) { + if !bytes.Equal(secret1, secret2) { t.Errorf("ECDH failed, secrets mismatch - first: %x, second: %x", secret1, secret2) } diff --git a/ec/secp256k1/ellipticadaptor.go b/ec/secp256k1/ellipticadaptor.go index 9d6fe2e..6cb615f 100644 --- a/ec/secp256k1/ellipticadaptor.go +++ b/ec/secp256k1/ellipticadaptor.go @@ -25,12 +25,12 @@ type CurveParams struct { // Gx and Gy are the x and y coordinate of the base point, respectively. Gx, Gy *big.Int // BitSize is the size of the underlying secp256k1 field in bits. - BitSize no + BitSize int // H is the cofactor of the secp256k1 curve. - H no + H int // ByteSize is simply the bit size / 8 and is provided for convenience // since it is calculated repeatedly. - ByteSize no + ByteSize int } // Curve parameters taken from [SECG] section 2.4.1. @@ -83,7 +83,7 @@ func (curve *KoblitzCurve) Params() *elliptic.CurveParams { // // This is part of the elliptic.Curve interface implementation. This function // differs from the crypto/elliptic algorithm since a = 0 not -3. -func (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bo { +func (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bool { // Convert big ints to a Jacobian point for faster arithmetic. var point JacobianPoint bigAffineToJacobian(x, y, &point) @@ -131,7 +131,7 @@ func (curve *KoblitzCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { // moduloReduce reduces k from more than 32 bytes to 32 bytes and under. This // is done by doing a simple modulo curve.N. We can do this since G^N = 1 and // thus any other valid point on the elliptic curve has the same order. -func moduloReduce(k by) by { +func moduloReduce(k []byte) []byte { // Since the order of G is curve.N, we can use a much smaller number by // doing modulo curve.N if len(k) > curveParams.ByteSize { @@ -145,7 +145,7 @@ func moduloReduce(k by) by { // ScalarMult returns k*(Bx, By) where k is a big endian integer. // // This is part of the elliptic.Curve interface implementation. -func (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k by) (*big.Int, +func (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { // Convert the affine coordinates from big integers to Jacobian points, // do the multiplication in Jacobian projective space, and convert the @@ -162,7 +162,7 @@ func (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k by) (*big.Int, // big endian integer. // // This is part of the elliptic.Curve interface implementation. -func (curve *KoblitzCurve) ScalarBaseMult(k by) (*big.Int, *big.Int) { +func (curve *KoblitzCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { // Perform the multiplication and convert the Jacobian point back to affine // big.Ints. var kModN ModNScalar @@ -214,7 +214,7 @@ func (p *SecretKey) ToECDSA() *ecdsa.PrivateKey { // panic is there is an error. This is only provided for the hard-coded // constants so errors in the source code can bet detected. It will only (and // must only) be called for initialization purposes. -func fromHex(s st) *big.Int { +func fromHex(s string) *big.Int { if s == "" { return big.NewInt(0) } diff --git a/ec/secp256k1/ellipticadaptor_test.go b/ec/secp256k1/ellipticadaptor_test.go index 39972c6..f6bd382 100644 --- a/ec/secp256k1/ellipticadaptor_test.go +++ b/ec/secp256k1/ellipticadaptor_test.go @@ -13,10 +13,10 @@ import ( // randBytes returns a byte slice of the required size created from a random // value generated by the passed rng. -func randBytes(t *testing.T, rng *rand.Rand, numBytes uint8) by { +func randBytes(t *testing.T, rng *rand.Rand, numBytes uint8) []byte { t.Helper() - buf := make(by, numBytes) + buf := make([]byte, numBytes) if _, err := rng.Read(buf); chk.T(err) { t.Fatalf("failed to read random: %v", err) } @@ -35,7 +35,7 @@ func TestIsOnCurveAdaptor(t *testing.T) { // isValidAffinePoint returns true if the point (x,y) is on the secp256k1 curve // or is the point at infinity. -func isValidAffinePoint(x, y *big.Int) bo { +func isValidAffinePoint(x, y *big.Int) bool { if x.Sign() == 0 && y.Sign() == 0 { return true } diff --git a/ec/secp256k1/error.go b/ec/secp256k1/error.go index 3a04a95..88a7030 100644 --- a/ec/secp256k1/error.go +++ b/ec/secp256k1/error.go @@ -40,7 +40,7 @@ func (err ErrorKind) Error() string { return string(err) } // caller can ascertain the specific reason for the error by checking // the underlying error. type Error struct { - Err er + Err error Description string } @@ -48,9 +48,9 @@ type Error struct { func (err Error) Error() string { return err.Description } // Unwrap returns the underlying wrapped error. -func (err Error) Unwrap() (ee er) { return err.Err } +func (err Error) Unwrap() (ee error) { return err.Err } // makeError creates an Error given a set of arguments. -func makeError(kind ErrorKind, desc string) (err er) { +func makeError(kind ErrorKind, desc string) (err error) { return Error{Err: kind, Description: desc} } diff --git a/ec/secp256k1/error_test.go b/ec/secp256k1/error_test.go index 358d821..b615270 100644 --- a/ec/secp256k1/error_test.go +++ b/ec/secp256k1/error_test.go @@ -56,10 +56,10 @@ func TestError(t *testing.T) { // a specific error kind via errors.Is and unwrapped via errors.As. func TestErrorKindIsAs(t *testing.T) { tests := []struct { - name st - err er - target er - wantMatch bo + name string + err error + target error + wantMatch bool wantAs ErrorKind }{{ name: "ErrPubKeyInvalidLen == ErrPubKeyInvalidLen", diff --git a/ec/secp256k1/example_test.go b/ec/secp256k1/example_test.go index 62e007b..4551f41 100644 --- a/ec/secp256k1/example_test.go +++ b/ec/secp256k1/example_test.go @@ -20,7 +20,7 @@ import ( // for a recipient's public key, and subsequently decrypt the message using the // recipient's secret key. func Example_encryptDecryptMessage() { - newAEAD := func(key by) (cipher.AEAD, er) { + newAEAD := func(key []byte) (cipher.AEAD, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err @@ -65,14 +65,14 @@ func Example_encryptDecryptMessage() { // is no key reuse and AES-GCM permits the nonce to be used as a counter, // the nonce is intentionally initialized to all zeros so it acts like the // first (and only) use of a counter. - plaintext := by("test message") + plaintext := []byte("test message") aead, err := newAEAD(cipherKey[:]) if err != nil { fmt.Println(err) return } - nonce := make(by, aead.NonceSize()) - ciphertext := make(by, 4+len(ephemeralPubKey)) + nonce := make([]byte, aead.NonceSize()) + ciphertext := make([]byte, 4+len(ephemeralPubKey)) binary.LittleEndian.PutUint32(ciphertext, uint32(len(ephemeralPubKey))) copy(ciphertext[4:], ephemeralPubKey) ciphertext = aead.Seal(ciphertext, nonce, plaintext, ephemeralPubKey) @@ -107,14 +107,14 @@ func Example_encryptDecryptMessage() { fmt.Println(err) return } - nonce = make(by, aead.NonceSize()) + nonce = make([]byte, aead.NonceSize()) recoveredPlaintext, err := aead.Open(nil, nonce, ciphertext[4+pubKeyLen:], senderPubKeyBytes) if err != nil { fmt.Println(err) return } - fmt.Println(st(recoveredPlaintext)) + fmt.Println(string(recoveredPlaintext)) // Output: // test message } diff --git a/ec/secp256k1/field.go b/ec/secp256k1/field.go index 9ddcaf1..c9c1918 100644 --- a/ec/secp256k1/field.go +++ b/ec/secp256k1/field.go @@ -309,7 +309,7 @@ func (f *FieldVal) SetBytes(b *[32]byte) uint32 { // Preconditions: None // Output Normalized: Yes if no overflow, no otherwise // Output Max Magnitude: 1 -func (f *FieldVal) SetByteSlice(b by) bo { +func (f *FieldVal) SetByteSlice(b []byte) bool { var b32 [32]byte b = b[:constantTimeMin(uint32(len(b)), 32)] copy(b32[:], b32[:32-len(b)]) @@ -437,7 +437,7 @@ func (f *FieldVal) Normalize() *FieldVal { // Preconditions: // - The field value MUST be normalized // - The target slice MUST have at least 32 bytes available -func (f *FieldVal) PutBytesUnchecked(b by) { +func (f *FieldVal) PutBytesUnchecked(b []byte) { // Unpack the 256 total bits from the 10 uint32 words with a max of // 26-bits per word. This could be done with a couple of for loops, // but this unrolled version is a bit faster. Benchmarks show this is @@ -530,7 +530,7 @@ func (f *FieldVal) IsZeroBit() uint32 { // // Preconditions: // - The field value MUST be normalized -func (f *FieldVal) IsZero() bo { +func (f *FieldVal) IsZero() bool { // The value can only be zero if no bits are set in any of the words. // This is a constant time implementation. bits := f.n[0] | f.n[1] | f.n[2] | f.n[3] | f.n[4] | @@ -563,7 +563,7 @@ func (f *FieldVal) IsOneBit() uint32 { // // Preconditions: // - The field value MUST be normalized -func (f *FieldVal) IsOne() bo { +func (f *FieldVal) IsOne() bool { // The value can only be one if the single lowest significant bit is set in // the first word and no other bits are set in any of the other words. // This is a constant time implementation. @@ -593,7 +593,7 @@ func (f *FieldVal) IsOddBit() uint32 { // // Preconditions: // - The field value MUST be normalized -func (f *FieldVal) IsOdd() bo { +func (f *FieldVal) IsOdd() bool { // Only odd numbers have the bottom bit set. return f.n[0]&1 == 1 } @@ -603,7 +603,7 @@ func (f *FieldVal) IsOdd() bo { // // Preconditions: // - Both field values being compared MUST be normalized -func (f *FieldVal) Equals(val *FieldVal) bo { +func (f *FieldVal) Equals(val *FieldVal) bool { // Xor only sets bits when they are different, so the two field values // can only be the same if no bits are set after xoring each word. // This is a constant time implementation. @@ -1065,7 +1065,7 @@ func (f *FieldVal) Mul2(val *FieldVal, val2 *FieldVal) *FieldVal { // - The input field value MUST have a max magnitude of 8 // Output Normalized: No // Output Max Magnitude: 1 -func (f *FieldVal) SquareRootVal(val *FieldVal) bo { +func (f *FieldVal) SquareRootVal(val *FieldVal) bool { // This uses the Tonelli-Shanks method for calculating the square root of // the value when it exists. The key principles of the method follow. // @@ -1551,7 +1551,7 @@ func (f *FieldVal) Inverse() *FieldVal { // // Preconditions: // - The field value MUST be normalized -func (f *FieldVal) IsGtOrEqPrimeMinusOrder() bo { +func (f *FieldVal) IsGtOrEqPrimeMinusOrder() bool { // The secp256k1 prime is equivalent to 2^256 - 4294968273 and the group // order is 2^256 - 432420386565659656852420866394968145599. Thus, // the prime minus the group order is: diff --git a/ec/secp256k1/field_test.go b/ec/secp256k1/field_test.go index e912e3c..d126ac2 100644 --- a/ec/secp256k1/field_test.go +++ b/ec/secp256k1/field_test.go @@ -7,6 +7,7 @@ package secp256k1 import ( + "bytes" "fmt" "math/big" "math/rand" @@ -98,10 +99,10 @@ func TestFieldSetInt(t *testing.T) { // edge cases. Random cases are tested via the various other tests. func TestFieldSetBytes(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded test value + name string // test description + in string // hex encoded test value expected [10]uint32 // expected raw ints - overflow bo // expected overflow result + overflow bool // expected overflow result }{{ name: "zero", in: "00", @@ -331,7 +332,7 @@ func TestFieldBytes(t *testing.T) { expected := hexToBytes(test.expected) // Ensure getting the bytes works as expected. gotBytes := f.Bytes() - if !equals(gotBytes[:], expected) { + if !bytes.Equal(gotBytes[:], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, *gotBytes, expected) continue @@ -339,7 +340,7 @@ func TestFieldBytes(t *testing.T) { // Ensure getting the bytes directly into an array works as expected. var b32 [32]byte f.PutBytes(&b32) - if !equals(b32[:], expected) { + if !bytes.Equal(b32[:], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, b32, expected) continue @@ -347,7 +348,7 @@ func TestFieldBytes(t *testing.T) { // Ensure getting the bytes directly into a slice works as expected. var buffer [64]byte f.PutBytesUnchecked(buffer[:]) - if !equals(buffer[:32], expected) { + if !bytes.Equal(buffer[:32], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, buffer[:32], expected) continue @@ -408,8 +409,8 @@ func TestFieldIsOne(t *testing.T) { tests := []struct { name string // test description in string // hex encoded test value - normalize bo // whether or not to normalize the test value - expected bo // expected result + normalize bool // whether or not to normalize the test value + expected bool // expected result }{{ name: "zero", in: "0", @@ -932,7 +933,7 @@ func TestFieldIsOdd(t *testing.T) { tests := []struct { name string // test description in string // hex encoded value - expected bo // expected oddness + expected bool // expected oddness }{{ name: "zero", in: "0", @@ -983,10 +984,10 @@ func TestFieldIsOdd(t *testing.T) { // Equals works as expected. func TestFieldEquals(t *testing.T) { tests := []struct { - name st // test description - in1 st // hex encoded value - in2 st // hex encoded value - expected bo // expected equality + name string // test description + in1 string // hex encoded value + in2 string // hex encoded value + expected bool // expected equality }{{ name: "0 == 0?", in1: "0", @@ -1507,10 +1508,10 @@ func TestFieldSquare(t *testing.T) { // via SquareRootVal works as expected for edge cases. func TestFieldSquareRoot(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded value - valid bo // whether the value has a square root - want st // expected hex encoded value + name string // test description + in string // hex encoded value + valid bool // whether the value has a square root + want string // expected hex encoded value }{{ name: "secp256k1 prime (as 0 in and out)", in: "0", @@ -1700,9 +1701,9 @@ func TestFieldInverse(t *testing.T) { // as expected for edge cases. func TestFieldIsGtOrEqPrimeMinusOrder(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded test value - expected bo // expected result + name string // test description + in string // hex encoded test value + expected bool // expected result }{{ name: "zero", in: "0", diff --git a/ec/secp256k1/modnscalar.go b/ec/secp256k1/modnscalar.go index 93ba37f..08a7e2f 100644 --- a/ec/secp256k1/modnscalar.go +++ b/ec/secp256k1/modnscalar.go @@ -190,7 +190,7 @@ func (s *ModNScalar) IsZeroBit() uint32 { } // IsZero returns whether or not the scalar is equal to zero in constant time. -func (s *ModNScalar) IsZero() bo { +func (s *ModNScalar) IsZero() bool { // The scalar can only be zero if no bits are set in any of the words. bits := s.n[0] | s.n[1] | s.n[2] | s.n[3] | s.n[4] | s.n[5] | s.n[6] | s.n[7] return bits == 0 @@ -351,7 +351,7 @@ func zeroArray32(b *[32]byte) { copy(b[:], zero32[:]) } // the caller to decide whether it needs to provide numbers of the appropriate // size or it is acceptable to use this function with the described truncation // and overflow behavior. -func (s *ModNScalar) SetByteSlice(b by) bo { +func (s *ModNScalar) SetByteSlice(b []byte) bool { var b32 [32]byte b = b[:constantTimeMin(uint32(len(b)), 32)] copy(b32[:], b32[:32-len(b)]) @@ -372,7 +372,7 @@ func (s *ModNScalar) SetByteSlice(b by) bo { // // Preconditions: // - The target slice MUST have at least 32 bytes available -func (s *ModNScalar) PutBytesUnchecked(b by) { +func (s *ModNScalar) PutBytesUnchecked(b []byte) { // Unpack the 256 total bits from the 8 uint32 words. This could be done // with a for loop, but benchmarks show this unrolled version is about 2 // times faster than the variant which uses a loop. @@ -435,13 +435,13 @@ func (s *ModNScalar) Bytes() [32]byte { } // IsOdd returns whether the scalar is an odd number in constant time. -func (s *ModNScalar) IsOdd() bo { +func (s *ModNScalar) IsOdd() bool { // Only odd numbers have the bottom bit set. return s.n[0]&1 == 1 } // Equals returns whether or not the two scalars are the same in constant time. -func (s *ModNScalar) Equals(val *ModNScalar) bo { +func (s *ModNScalar) Equals(val *ModNScalar) bool { // Xor only sets bits when they are different, so the two scalars can only // be the same if no bits are set after xoring each word. bits := (s.n[0] ^ val.n[0]) | (s.n[1] ^ val.n[1]) | (s.n[2] ^ val.n[2]) | @@ -1028,7 +1028,7 @@ func (s *ModNScalar) InverseNonConst() *ModNScalar { // IsOverHalfOrder returns whether the scalar exceeds the group order // divided by 2 in constant time. -func (s *ModNScalar) IsOverHalfOrder() bo { +func (s *ModNScalar) IsOverHalfOrder() bool { // The intuition here is that the scalar is greater than half of the group // order if one of the higher individual words is greater than the // corresponding word of the half group order and all higher words in the diff --git a/ec/secp256k1/modnscalar_bench_test.go b/ec/secp256k1/modnscalar_bench_test.go index 850968e..847734f 100644 --- a/ec/secp256k1/modnscalar_bench_test.go +++ b/ec/secp256k1/modnscalar_bench_test.go @@ -11,8 +11,8 @@ import ( // benchmarkVals returns the raw bytes for a couple of unsigned 256-bit // big-endian integers used throughout the benchmarks. -func benchmarkVals() [2]by { - return [2]by{ +func benchmarkVals() [2][]byte { + return [2][]byte{ hexToBytes("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364143"), hexToBytes("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364144"), } diff --git a/ec/secp256k1/modnscalar_test.go b/ec/secp256k1/modnscalar_test.go index 1655136..4800b39 100644 --- a/ec/secp256k1/modnscalar_test.go +++ b/ec/secp256k1/modnscalar_test.go @@ -5,6 +5,7 @@ package secp256k1 import ( + "bytes" "fmt" "math/big" "math/rand" @@ -154,7 +155,7 @@ func TestModNScalarSetBytes(t *testing.T) { name string // test description in string // hex encoded test value expected [8]uint32 // expected raw ints - overflow bo // expected overflow result + overflow bool // expected overflow result }{{ name: "zero", in: "00", @@ -285,10 +286,10 @@ func TestModNScalarSetBytes(t *testing.T) { // edge cases. Random cases are tested via the various other tests. func TestModNScalarBytes(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded test value - expected st // expected hex encoded bytes - overflow bo // expected overflow result + name string // test description + in string // hex encoded test value + expected string // expected hex encoded bytes + overflow bool // expected overflow result }{{ name: "zero", in: "0", @@ -347,7 +348,7 @@ func TestModNScalarBytes(t *testing.T) { expected := hexToBytes(test.expected) // Ensure getting the bytes works as expected. gotBytes := s.Bytes() - if !equals(gotBytes[:], expected) { + if !bytes.Equal(gotBytes[:], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, gotBytes, expected) continue @@ -355,7 +356,7 @@ func TestModNScalarBytes(t *testing.T) { // Ensure getting the bytes directly into an array works as expected. var b32 [32]byte s.PutBytes(&b32) - if !equals(b32[:], expected) { + if !bytes.Equal(b32[:], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, b32, expected) continue @@ -363,7 +364,7 @@ func TestModNScalarBytes(t *testing.T) { // Ensure getting the bytes directly into a slice works as expected. var buffer [64]byte s.PutBytesUnchecked(buffer[:]) - if !equals(buffer[:32], expected) { + if !bytes.Equal(buffer[:32], expected) { t.Errorf("%s: unexpected result\ngot: %x\nwant: %x", test.name, buffer[:32], expected) continue @@ -375,9 +376,9 @@ func TestModNScalarBytes(t *testing.T) { // expected. func TestModNScalarIsOdd(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded value - expected bo // expected oddness + name string // test description + in string // hex encoded value + expected bool // expected oddness }{{ name: "zero", in: "0", @@ -421,10 +422,10 @@ func TestModNScalarIsOdd(t *testing.T) { // expected for edge cases. func TestModNScalarEquals(t *testing.T) { tests := []struct { - name st // test description - in1 st // hex encoded value - in2 st // hex encoded value - expected bo // expected equality + name string // test description + in1 string // hex encoded value + in2 string // hex encoded value + expected bool // expected equality }{{ name: "0 == 0?", in1: "0", @@ -1157,9 +1158,9 @@ func TestModNScalarInverseNonConstRandom(t *testing.T) { // exceeed the half order works as expected for edge cases. func TestModNScalarIsOverHalfOrder(t *testing.T) { tests := []struct { - name st // test description - in st // hex encoded test value - expected bo // expected result + name string // test description + in string // hex encoded test value + expected bool // expected result }{{ name: "zero", in: "0", diff --git a/ec/secp256k1/nonce.go b/ec/secp256k1/nonce.go index 342eb3e..ac180dc 100644 --- a/ec/secp256k1/nonce.go +++ b/ec/secp256k1/nonce.go @@ -25,16 +25,16 @@ import ( var ( // singleZero is used during RFC6979 nonce generation. It is provided // here to avoid the need to create it multiple times. - singleZero = by{0x00} + singleZero = []byte{0x00} // zeroInitializer is used during RFC6979 nonce generation. It is provided // here to avoid the need to create it multiple times. - zeroInitializer = bytes.Repeat(by{0x00}, sha256.BlockSize) + zeroInitializer = bytes.Repeat([]byte{0x00}, sha256.BlockSize) // singleOne is used during RFC6979 nonce generation. It is provided // here to avoid the need to create it multiple times. - singleOne = by{0x01} + singleOne = []byte{0x01} // oneInitializer is used during RFC6979 nonce generation. It is provided // here to avoid the need to create it multiple times. - oneInitializer = bytes.Repeat(by{0x01}, sha256.Size) + oneInitializer = bytes.Repeat([]byte{0x01}, sha256.Size) ) // hmacsha256 implements a resettable version of HMAC-SHA256. @@ -44,10 +44,10 @@ type hmacsha256 struct { } // Write adds data to the running hash. -func (h *hmacsha256) Write(p by) { h.inner.Write(p) } +func (h *hmacsha256) Write(p []byte) { h.inner.Write(p) } // initKey initializes the HMAC-SHA256 instance to the provided key. -func (h *hmacsha256) initKey(key by) { +func (h *hmacsha256) initKey(key []byte) { // Hash the key if it is too large. if len(key) > sha256.BlockSize { h.outer.Write(key) @@ -67,7 +67,7 @@ func (h *hmacsha256) initKey(key by) { // ResetKey resets the HMAC-SHA256 to its initial state and then initializes it // with the provided key. It is equivalent to creating a new instance with the // provided key without allocating more memory. -func (h *hmacsha256) ResetKey(key by) { +func (h *hmacsha256) ResetKey(key []byte) { h.inner.Reset() h.outer.Reset() copy(h.ipad[:], zeroInitializer) @@ -82,7 +82,7 @@ func (h *hmacsha256) Reset() { } // Sum returns the hash of the written data. -func (h *hmacsha256) Sum() by { +func (h *hmacsha256) Sum() []byte { h.outer.Reset() h.outer.Write(h.opad[:]) h.outer.Write(h.inner.Sum(nil)) @@ -90,7 +90,7 @@ func (h *hmacsha256) Sum() by { } // newHMACSHA256 returns a new HMAC-SHA256 hasher using the provided key. -func newHMACSHA256(key by) *hmacsha256 { +func newHMACSHA256(key []byte) *hmacsha256 { h := new(hmacsha256) h.inner = sha256.New() h.outer = sha256.New() @@ -110,7 +110,7 @@ func newHMACSHA256(key by) *hmacsha256 { // that results in a valid signature in the extremely unlikely event the // original nonce produced results in an invalid signature (e.g. R == 0). // Signing code should start with 0 and increment it if necessary. -func NonceRFC6979(secKey by, hash by, extra by, version by, +func NonceRFC6979(secKey []byte, hash []byte, extra []byte, version []byte, extraIterations uint32) *ModNScalar { // Input to HMAC is the 32-byte secret key and the 32-byte hash. In // addition, it may include the optional 32-byte extra data and 16-byte diff --git a/ec/secp256k1/nonce_test.go b/ec/secp256k1/nonce_test.go index 5fce5da..745a2f6 100644 --- a/ec/secp256k1/nonce_test.go +++ b/ec/secp256k1/nonce_test.go @@ -6,6 +6,7 @@ package secp256k1 import ( + "bytes" "testing" "realy.lol/hex" @@ -16,7 +17,7 @@ import ( // is an error. This is only provided for the hard-coded constants so errors in // the source code can be detected. It will only (and must only) be called with // hard-coded values. -func hexToBytes(s string) by { +func hexToBytes(s string) []byte { b, err := hex.Dec(s) if err != nil { panic("invalid hex in source file: " + s) @@ -151,7 +152,7 @@ func TestNonceRFC6979(t *testing.T) { gotNonce := NonceRFC6979(secKey, hash[:], extraData, version, test.iterations) gotNonceBytes := gotNonce.Bytes() - if !equals(gotNonceBytes[:], wantNonce) { + if !bytes.Equal(gotNonceBytes[:], wantNonce) { t.Errorf("%s: unexpected nonce -- got %x, want %x", test.name, gotNonceBytes, wantNonce) continue @@ -199,12 +200,12 @@ func TestRFC6979Compat(t *testing.T) { }} for i, test := range tests { secKey := hexToBytes(test.key) - hash := sha256.Sum256(by(test.msg)) + hash := sha256.Sum256([]byte(test.msg)) // Ensure deterministically generated nonce is the expected value. gotNonce := NonceRFC6979(secKey, hash[:], nil, nil, 0) wantNonce := hexToBytes(test.nonce) gotNonceBytes := gotNonce.Bytes() - if !equals(gotNonceBytes[:], wantNonce) { + if !bytes.Equal(gotNonceBytes[:], wantNonce) { t.Errorf("NonceRFC6979 #%d (%s): Nonce is incorrect: "+ "%x (expected %x)", i, test.msg, gotNonce, wantNonce) diff --git a/ec/secp256k1/precomps.go b/ec/secp256k1/precomps.go index 7e10ddd..4ac19e0 100644 --- a/ec/secp256k1/precomps.go +++ b/ec/secp256k1/precomps.go @@ -5,11 +5,11 @@ import ( ) //go:embed rawbytepoints.bin -var bytepoints by +var bytepoints []byte var BytePointTable [32][256]JacobianPoint func init() { - var cursor no + var cursor int for i := range BytePointTable { for j := range BytePointTable[i] { BytePointTable[i][j].X.SetByteSlice(bytepoints[cursor:]) diff --git a/ec/secp256k1/precomps/genprecomps.go b/ec/secp256k1/precomps/genprecomps.go index 1b57650..a8bd5a8 100644 --- a/ec/secp256k1/precomps/genprecomps.go +++ b/ec/secp256k1/precomps/genprecomps.go @@ -29,7 +29,7 @@ func bigAffineToJacobian(x, y *big.Int, result *secp256k1.JacobianPoint) { // serializedBytePoints returns a serialized byte slice which contains all possible points per // 8-bit window. This is used to when generating compressedbytepoints.go. -func serializedBytePoints() by { +func serializedBytePoints() []byte { // Calculate G^(2^i) for i in 0..255. These are used to avoid recomputing // them for each digit of the 8-bit windows. doublingPoints := make([]secp256k1.JacobianPoint, curveParams.BitSize) @@ -43,7 +43,7 @@ func serializedBytePoints() by { // Separate the bits into byte-sized windows. curveByteSize := curveParams.BitSize / 8 - serialized := make(by, curveByteSize*256*2*32) + serialized := make([]byte, curveByteSize*256*2*32) offset := 0 for byteNum := 0; byteNum < curveByteSize; byteNum++ { // Grab the 8 bits that make up this byte from doubling points. diff --git a/ec/secp256k1/precomps/util.go b/ec/secp256k1/precomps/util.go index 6e09e1f..03d0211 100644 --- a/ec/secp256k1/precomps/util.go +++ b/ec/secp256k1/precomps/util.go @@ -1,22 +1,9 @@ package main import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/secp256k1/pubkey.go b/ec/secp256k1/pubkey.go index b8ffbce..8512e25 100644 --- a/ec/secp256k1/pubkey.go +++ b/ec/secp256k1/pubkey.go @@ -100,7 +100,7 @@ func NewPublicKey(x, y *FieldVal) *PublicKey { // NOTE: The hybrid format makes little sense in practice an therefore this // package will not produce public keys serialized in this format. However, // this function will properly parse them since they exist in the wild. -func ParsePubKey(serialized by) (key *PublicKey, err er) { +func ParsePubKey(serialized []byte) (key *PublicKey, err error) { var x, y FieldVal switch len(serialized) { case PubKeyBytesLenUncompressed: @@ -176,7 +176,7 @@ func ParsePubKey(serialized by) (key *PublicKey, err er) { // SerializeUncompressed serializes a public key in the 65-byte uncompressed // format. -func (p PublicKey) SerializeUncompressed() by { +func (p PublicKey) SerializeUncompressed() []byte { // 0x04 || 32-byte x coordinate || 32-byte y coordinate var b [PubKeyBytesLenUncompressed]byte b[0] = PubKeyFormatUncompressed @@ -186,7 +186,7 @@ func (p PublicKey) SerializeUncompressed() by { } // SerializeCompressed serializes a public key in the 33-byte compressed format. -func (p PublicKey) SerializeCompressed() by { +func (p PublicKey) SerializeCompressed() []byte { // Choose the format byte depending on the oddness of the Y coordinate. format := PubKeyFormatCompressedEven if p.y.IsOdd() { @@ -202,7 +202,7 @@ func (p PublicKey) SerializeCompressed() by { // IsEqual compares this public key instance to the one passed, returning true // if both public keys are equivalent. A public key is equivalent to another, // if they both have the same X and Y coordinates. -func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bo { +func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool { return p.x.Equals(&otherPubKey.x) && p.y.Equals(&otherPubKey.y) } @@ -217,6 +217,6 @@ func (p *PublicKey) AsJacobian(result *JacobianPoint) { // IsOnCurve returns whether or not the public key represents a point on the // secp256k1 curve. -func (p *PublicKey) IsOnCurve() bo { +func (p *PublicKey) IsOnCurve() bool { return isOnCurve(&p.x, &p.y) } diff --git a/ec/secp256k1/pubkey_test.go b/ec/secp256k1/pubkey_test.go index 36a559a..6480d57 100644 --- a/ec/secp256k1/pubkey_test.go +++ b/ec/secp256k1/pubkey_test.go @@ -6,6 +6,7 @@ package secp256k1 import ( + "bytes" "errors" "testing" ) @@ -14,11 +15,11 @@ import ( // to the spec including both the positive and negative cases. func TestParsePubKey(t *testing.T) { tests := []struct { - name st // test description - key st // hex encoded public key - err er // expected error - wantX st // expected x coordinate - wantY st // expected y coordinate + name string // test description + key string // hex encoded public key + err error // expected error + wantX string // expected x coordinate + wantY string // expected y coordinate }{{ name: "uncompressed ok", key: "04" + @@ -231,11 +232,11 @@ func TestParsePubKey(t *testing.T) { // for both the compressed and uncompressed cases. func TestPubKeySerialize(t *testing.T) { tests := []struct { - name st // test description - pubX st // hex encoded x coordinate for pubkey to serialize - pubY st // hex encoded y coordinate for pubkey to serialize - compress bo // whether to serialize compressed or uncompressed - expected st // hex encoded expected pubkey serialization + name string // test description + pubX string // hex encoded x coordinate for pubkey to serialize + pubY string // hex encoded y coordinate for pubkey to serialize + compress bool // whether to serialize compressed or uncompressed + expected string // hex encoded expected pubkey serialization }{{ name: "uncompressed (ybit = 0)", pubX: "11db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5c", @@ -315,14 +316,14 @@ func TestPubKeySerialize(t *testing.T) { pubKey := NewPublicKey(x, y) // Serialize with the correct method and ensure the result matches the // expected value. - var serialized by + var serialized []byte if test.compress { serialized = pubKey.SerializeCompressed() } else { serialized = pubKey.SerializeUncompressed() } expected := hexToBytes(test.expected) - if !equals(serialized, expected) { + if !bytes.Equal(serialized, expected) { t.Errorf("%s: mismatched serialized public key -- got %x, want %x", test.name, serialized, expected) continue @@ -365,10 +366,10 @@ func TestPublicKeyIsEqual(t *testing.T) { // with a Z coordinate of 1 works as expected. func TestPublicKeyAsJacobian(t *testing.T) { tests := []struct { - name st // test description - pubKey st // hex encoded serialized compressed pubkey - wantX st // hex encoded expected X coordinate - wantY st // hex encoded expected Y coordinate + name string // test description + pubKey string // hex encoded serialized compressed pubkey + wantX string // hex encoded expected X coordinate + wantY string // hex encoded expected Y coordinate }{{ name: "public key for secret key 0x01", pubKey: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", @@ -421,10 +422,10 @@ func TestPublicKeyAsJacobian(t *testing.T) { // as expected. func TestPublicKeyIsOnCurve(t *testing.T) { tests := []struct { - name st // test description - pubX st // hex encoded x coordinate for pubkey to serialize - pubY st // hex encoded y coordinate for pubkey to serialize - want bo // expected result + name string // test description + pubX string // hex encoded x coordinate for pubkey to serialize + pubY string // hex encoded y coordinate for pubkey to serialize + want bool // expected result }{{ name: "valid with even y", pubX: "11db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5c", diff --git a/ec/secp256k1/seckey.go b/ec/secp256k1/seckey.go index 6ae6e4e..29c9cbc 100644 --- a/ec/secp256k1/seckey.go +++ b/ec/secp256k1/seckey.go @@ -46,7 +46,7 @@ var NewPrivateKey = NewSecretKey // Typically, callers should make use of GenerateSecretKey or // GenerateSecretKeyFromRand when creating secret keys since they properly // handle generation of appropriate values. -func SecKeyFromBytes(secKeyBytes by) *SecretKey { +func SecKeyFromBytes(secKeyBytes []byte) *SecretKey { var secKey SecretKey secKey.Key.SetByteSlice(secKeyBytes) return &secKey @@ -58,7 +58,7 @@ var PrivKeyFromBytes = SecKeyFromBytes // for use with secp256k1 using the provided reader as a source of entropy. The // provided reader must be a source of cryptographically secure randomness to // avoid weak secret keys. -func generateSecretKey(rand io.Reader) (*SecretKey, er) { +func generateSecretKey(rand io.Reader) (*SecretKey, error) { // The group order is close enough to 2^256 that there is only roughly a 1 // in 2^128 chance of generating an invalid secret key, so this loop will // virtually never run more than a single iteration in practice. @@ -79,7 +79,7 @@ func generateSecretKey(rand io.Reader) (*SecretKey, er) { // GenerateSecretKey generates and returns a new cryptographically secure secret key that is suitable for use with // secp256k1. -func GenerateSecretKey() (*SecretKey, er) { +func GenerateSecretKey() (*SecretKey, error) { return generateSecretKey(rand.Reader) } @@ -92,7 +92,7 @@ var GeneratePrivateKey = GenerateSecretKey // GenerateSecretKeyFromRand generates a secret key that is suitable for use with secp256k1 using the provided reader as // a source of entropy. The provided reader must be a source of cryptographically secure randomness, such as // [crypto/rand.Reader], to avoid weak secret keys. -func GenerateSecretKeyFromRand(rand io.Reader) (*SecretKey, er) { +func GenerateSecretKeyFromRand(rand io.Reader) (*SecretKey, error) { return generateSecretKey(rand) } @@ -121,7 +121,7 @@ const SecKeyBytesLen = 32 // Serialize returns the secret key as a 256-bit big-endian binary-encoded // number, padded to a length of 32 bytes. -func (p *SecretKey) Serialize() by { +func (p *SecretKey) Serialize() []byte { var secKeyBytes [SecKeyBytesLen]byte p.Key.PutBytes(&secKeyBytes) return secKeyBytes[:] diff --git a/ec/secp256k1/seckey_test.go b/ec/secp256k1/seckey_test.go index 797b4ca..08cc3ad 100644 --- a/ec/secp256k1/seckey_test.go +++ b/ec/secp256k1/seckey_test.go @@ -42,10 +42,10 @@ func TestGenerateSecretKeyFromRand(t *testing.T) { // mockSecretKeyReaderFunc is an adapter to allow the use of an ordinary // function as an io.Reader. -type mockSecretKeyReaderFunc func(by) (no, er) +type mockSecretKeyReaderFunc func([]byte) (int, error) // Read calls the function with the provided parameter and returns the result. -func (f mockSecretKeyReaderFunc) Read(p by) (no, er) { +func (f mockSecretKeyReaderFunc) Read(p []byte) (int, error) { return f(p) } @@ -60,12 +60,12 @@ func TestGenerateSecretKeyCorners(t *testing.T) { // 3rd invocation: The curve order + 1 // 4th invocation: 1 (32-byte big endian) oneModN := hexToModNScalar("01") - var numReads no - mockReader := mockSecretKeyReaderFunc(func(p by) (no, er) { + var numReads int + mockReader := mockSecretKeyReaderFunc(func(p []byte) (int, error) { numReads++ switch numReads { case 1: - return copy(p, bytes.Repeat(by{0x00}, len(p))), nil + return copy(p, bytes.Repeat([]byte{0x00}, len(p))), nil case 2: return copy(p, curveParams.N.Bytes()), nil case 3: @@ -94,7 +94,7 @@ func TestGenerateSecretKeyCorners(t *testing.T) { func TestGenerateSecretKeyError(t *testing.T) { // Create a mock reader that returns an error. errDisabled := errors.New("disabled") - mockReader := mockSecretKeyReaderFunc(func(p by) (no, er) { + mockReader := mockSecretKeyReaderFunc(func(p []byte) (int, error) { return 0, errDisabled }) // Generate a secret key using the mock reader and ensure the expected @@ -110,9 +110,9 @@ func TestGenerateSecretKeyError(t *testing.T) { // correct associated public key as well serializes back to the original bytes. func TestSecKeys(t *testing.T) { tests := []struct { - name st - sec st // hex encoded secret key to test - pub st // expected hex encoded serialized compressed public key + name string + sec string // hex encoded secret key to test + pub string // expected hex encoded serialized compressed public key }{{ name: "random secret key 1", sec: "eaf02ca348c524e6392655ba4d29603cd1a7347d9d65cfe93ce1ebffdca22694", @@ -132,13 +132,13 @@ func TestSecKeys(t *testing.T) { pub := sec.PubKey() serializedPubKey := pub.SerializeCompressed() - if !equals(serializedPubKey, wantPubKeyBytes) { + if !bytes.Equal(serializedPubKey, wantPubKeyBytes) { t.Errorf("%s unexpected serialized public key - got: %x, want: %x", test.name, serializedPubKey, wantPubKeyBytes) } serializedSecKey := sec.Serialize() - if !equals(serializedSecKey, secKeyBytes) { + if !bytes.Equal(serializedSecKey, secKeyBytes) { t.Errorf("%s unexpected serialized secret key - got: %x, want: %x", test.name, serializedSecKey, secKeyBytes) } diff --git a/ec/secp256k1/util.go b/ec/secp256k1/util.go index 5ee6b49..9ba1da6 100644 --- a/ec/secp256k1/util.go +++ b/ec/secp256k1/util.go @@ -1,22 +1,9 @@ package secp256k1 import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/secp256k1/util_test.go b/ec/secp256k1/util_test.go index 0940961..de7f013 100644 --- a/ec/secp256k1/util_test.go +++ b/ec/secp256k1/util_test.go @@ -1,22 +1,9 @@ package secp256k1_test import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/taproot/taproot.go b/ec/taproot/taproot.go index 35960ca..c618932 100644 --- a/ec/taproot/taproot.go +++ b/ec/taproot/taproot.go @@ -11,9 +11,9 @@ import ( // AddressSegWit is the base address type for all SegWit addresses. type AddressSegWit struct { - hrp by + hrp []byte witnessVersion byte - witnessProgram by + witnessProgram []byte } // AddressTaproot is an Address for a pay-to-taproot (P2TR) output. See BIP 341 @@ -23,8 +23,8 @@ type AddressTaproot struct { } // NewAddressTaproot returns a new AddressTaproot. -func NewAddressTaproot(witnessProg by, - net *chaincfg.Params) (*AddressTaproot, er) { +func NewAddressTaproot(witnessProg []byte, + net *chaincfg.Params) (*AddressTaproot, error) { return newAddressTaproot(net.Bech32HRPSegwit, witnessProg) } @@ -32,7 +32,7 @@ func NewAddressTaproot(witnessProg by, // newAddressWitnessScriptHash is an internal helper function to create an // AddressWitnessScriptHash with a known human-readable part, rather than // looking it up through its parameters. -func newAddressTaproot(hrp by, witnessProg by) (*AddressTaproot, er) { +func newAddressTaproot(hrp []byte, witnessProg []byte) (*AddressTaproot, error) { // Check for valid program length for witness version 1, which is 32 // for P2TR. if len(witnessProg) != 32 { @@ -51,10 +51,10 @@ func newAddressTaproot(hrp by, witnessProg by) (*AddressTaproot, er) { // decodeSegWitAddress parses a bech32 encoded segwit address string and // returns the witness version and witness program byte representation. -func decodeSegWitAddress(address by) (byte, by, er) { +func decodeSegWitAddress(address []byte) (byte, []byte, error) { // Decode the bech32 encoded address. _, data, bech32version, err := bech32.DecodeGeneric(address) - if err != nil { + if chk.E(err) { return 0, nil, err } // The first byte of the decoded address is the witness version, it must @@ -71,7 +71,7 @@ func decodeSegWitAddress(address by) (byte, by, er) { // words of 5 bits. In order to restore the original witness program // bytes, we'll need to regroup into 8 bit words. regrouped, err := bech32.ConvertBits(data[1:], 5, 8, false) - if err != nil { + if chk.E(err) { return 0, nil, err } // The regrouped data must be between 2 and 40 bytes. @@ -98,20 +98,20 @@ func decodeSegWitAddress(address by) (byte, by, er) { // encodeSegWitAddress creates a bech32 (or bech32m for SegWit v1) encoded // address string representation from witness version and witness program. -func encodeSegWitAddress(hrp by, witnessVersion byte, - witnessProgram by) (by, er) { +func encodeSegWitAddress(hrp []byte, witnessVersion byte, + witnessProgram []byte) ([]byte, error) { // Group the address bytes into 5 bit groups, as this is what is used to // encode each character in the address string. converted, err := bech32.ConvertBits(witnessProgram, 8, 5, true) - if err != nil { + if chk.E(err) { return nil, err } // Concatenate the witness version and program, and encode the resulting // bytes using bech32 encoding. - combined := make(by, len(converted)+1) + combined := make([]byte, len(converted)+1) combined[0] = witnessVersion copy(combined[1:], converted) - var bech by + var bech []byte switch witnessVersion { case 0: bech, err = bech32.Encode(hrp, combined) @@ -123,15 +123,15 @@ func encodeSegWitAddress(hrp by, witnessVersion byte, return nil, fmt.Errorf("unsupported witness version %d", witnessVersion) } - if err != nil { + if chk.E(err) { return nil, err } // Check validity by decoding the created address. version, program, err := decodeSegWitAddress(bech) - if err != nil { + if chk.E(err) { return nil, fmt.Errorf("invalid segwit address: %v", err) } - if version != witnessVersion || !equals(program, witnessProgram) { + if version != witnessVersion || !bytes.Equal(program, witnessProgram) { return nil, fmt.Errorf("invalid segwit address") } return bech, nil @@ -141,11 +141,11 @@ func encodeSegWitAddress(hrp by, witnessVersion byte, // of an AddressSegWit. // // NOTE: This method is part of the Address interface. -func (a *AddressSegWit) EncodeAddress() by { +func (a *AddressSegWit) EncodeAddress() []byte { str, err := encodeSegWitAddress( a.hrp, a.witnessVersion, a.witnessProgram[:], ) - if err != nil { + if chk.E(err) { return nil } return str diff --git a/ec/taproot/util.go b/ec/taproot/util.go index 7c64523..bd99b63 100644 --- a/ec/taproot/util.go +++ b/ec/taproot/util.go @@ -1,22 +1,9 @@ package taproot import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/util.go b/ec/util.go index 486802f..81a7b84 100644 --- a/ec/util.go +++ b/ec/util.go @@ -1,22 +1,9 @@ package btcec import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/util_test.go b/ec/util_test.go index dbbaf91..e5d6674 100644 --- a/ec/util_test.go +++ b/ec/util_test.go @@ -1,22 +1,9 @@ package btcec_test import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/ec/wire/msgtx.go b/ec/wire/msgtx.go index f5a9225..fe0bf38 100644 --- a/ec/wire/msgtx.go +++ b/ec/wire/msgtx.go @@ -13,12 +13,12 @@ type OutPoint struct { // TxWitness defines the witness for a TxIn. A witness is to be interpreted as // a slice of byte slices, or a stack with one or many elements. -type TxWitness []by +type TxWitness [][]byte // TxIn defines a bitcoin transaction input. type TxIn struct { PreviousOutPoint OutPoint - SignatureScript by + SignatureScript []byte Witness TxWitness Sequence uint32 } @@ -26,7 +26,7 @@ type TxIn struct { // TxOut defines a bitcoin transaction output. type TxOut struct { Value int64 - PkScript by + PkScript []byte } // MsgTx implements the Message interface and represents a bitcoin tx message. diff --git a/ec/wire/util.go b/ec/wire/util.go index 78fec0b..8064bf4 100644 --- a/ec/wire/util.go +++ b/ec/wire/util.go @@ -1,22 +1,9 @@ package wire import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal ) diff --git a/encryption/nip4.go b/encryption/nip4.go index 5954058..06d51ce 100644 --- a/encryption/nip4.go +++ b/encryption/nip4.go @@ -8,14 +8,15 @@ import ( "strings" "lukechampine.com/frand" + "realy.lol/hex" "realy.lol/p256k" ) // ComputeSharedSecret returns a shared secret key used to encrypt messages. The private and public keys should be hex // encoded. Uses the Diffie-Hellman key exchange (ECDH) (RFC 4753). -func ComputeSharedSecret(pkh, skh st) (sharedSecret by, err er) { - var skb, pkb by +func ComputeSharedSecret(pkh, skh string) (sharedSecret []byte, err error) { + var skb, pkb []byte if skb, err = hex.Dec(skh); chk.E(err) { return } @@ -38,9 +39,9 @@ func ComputeSharedSecret(pkh, skh st) (sharedSecret by, err er) { // Returns: base64(encrypted_bytes) + "?iv=" + base64(initialization_vector). // // Deprecated: upgrade to using Decrypt with the NIP-44 algorithm. -func EncryptNip4(msg st, key by) (ct by, err er) { +func EncryptNip4(msg string, key []byte) (ct []byte, err error) { // block size is 16 bytes - iv := make(by, 16) + iv := make([]byte, 16) if _, err = frand.Read(iv); chk.E(err) { err = errorf.E("error creating initialization vector: %w", err) return @@ -52,18 +53,18 @@ func EncryptNip4(msg st, key by) (ct by, err er) { return } mode := cipher.NewCBCEncrypter(block, iv) - plaintext := by(msg) + plaintext := []byte(msg) // add padding base := len(plaintext) // this will be a number between 1 and 16 (inclusive), never 0 bs := block.BlockSize() padding := bs - base%bs // encode the padding in all the padding bytes themselves - padText := bytes.Repeat(by{byte(padding)}, padding) + padText := bytes.Repeat([]byte{byte(padding)}, padding) paddedMsgBytes := append(plaintext, padText...) - ciphertext := make(by, len(paddedMsgBytes)) + ciphertext := make([]byte, len(paddedMsgBytes)) mode.CryptBlocks(ciphertext, paddedMsgBytes) - return by(base64.StdEncoding.EncodeToString(ciphertext) + "?iv=" + + return []byte(base64.StdEncoding.EncodeToString(ciphertext) + "?iv=" + base64.StdEncoding.EncodeToString(iv)), nil } @@ -71,18 +72,18 @@ func EncryptNip4(msg st, key by) (ct by, err er) { // EncryptNip4(message, key). // // Deprecated: upgrade to using Decrypt with the NIP-44 algorithm. -func DecryptNip4(content st, key by) (msg by, err er) { +func DecryptNip4(content string, key []byte) (msg []byte, err error) { parts := strings.Split(content, "?iv=") if len(parts) < 2 { return nil, errorf.E( "error parsing encrypted message: no initialization vector") } - var ciphertext by + var ciphertext []byte if ciphertext, err = base64.StdEncoding.DecodeString(parts[0]); chk.E(err) { err = errorf.E("error decoding ciphertext from base64: %w", err) return } - var iv by + var iv []byte if iv, err = base64.StdEncoding.DecodeString(parts[1]); chk.E(err) { err = errorf.E("error decoding iv from base64: %w", err) return @@ -93,7 +94,7 @@ func DecryptNip4(content st, key by) (msg by, err er) { return } mode := cipher.NewCBCDecrypter(block, iv) - msg = make(by, len(ciphertext)) + msg = make([]byte, len(ciphertext)) mode.CryptBlocks(msg, ciphertext) // remove padding var ( @@ -101,7 +102,7 @@ func DecryptNip4(content st, key by) (msg by, err er) { ) if plaintextLen > 0 { // the padding amount is encoded in the padding bytes themselves - padding := no(msg[plaintextLen-1]) + padding := int(msg[plaintextLen-1]) if padding > plaintextLen { err = errorf.E("invalid padding amount: %d", padding) return diff --git a/encryption/nip44.go b/encryption/nip44.go index c547fb5..0f0e9e7 100644 --- a/encryption/nip44.go +++ b/encryption/nip44.go @@ -11,6 +11,7 @@ import ( "golang.org/x/crypto/chacha20" "golang.org/x/crypto/hkdf" + "realy.lol/sha256" ) @@ -21,14 +22,14 @@ const ( ) type Opts struct { - err er - nonce by + err error + nonce []byte } // Deprecated: use WithCustomNonce instead of WithCustomSalt, so the naming is less confusing var WithCustomSalt = WithCustomNonce -func WithCustomNonce(salt by) func(opts *Opts) { +func WithCustomNonce(salt []byte) func(opts *Opts) { return func(opts *Opts) { if len(salt) != 32 { opts.err = errorf.E("salt must be 32 bytes, got %d", len(salt)) @@ -37,9 +38,9 @@ func WithCustomNonce(salt by) func(opts *Opts) { } } -func Encrypt(plaintext st, conversationKey by, - applyOptions ...func(opts *Opts)) (cipherString st, - err er) { +func Encrypt(plaintext string, conversationKey []byte, + applyOptions ...func(opts *Opts)) (cipherString string, + err error) { var o Opts for _, apply := range applyOptions { apply(&o) @@ -49,34 +50,34 @@ func Encrypt(plaintext st, conversationKey by, return } if o.nonce == nil { - o.nonce = make(by, 32) + o.nonce = make([]byte, 32) if _, err = rand.Read(o.nonce); chk.E(err) { return } } - var enc, cc20nonce, auth by + var enc, cc20nonce, auth []byte if enc, cc20nonce, auth, err = getKeys(conversationKey, o.nonce); chk.E(err) { return } - plain := by(plaintext) + plain := []byte(plaintext) size := len(plain) if size < MinPlaintextSize || size > MaxPlaintextSize { err = errorf.E("plaintext should be between 1b and 64kB") return } padding := calcPadding(size) - padded := make(by, 2+padding) + padded := make([]byte, 2+padding) binary.BigEndian.PutUint16(padded, uint16(size)) copy(padded[2:], plain) - var cipher by + var cipher []byte if cipher, err = encrypt(enc, cc20nonce, padded); chk.E(err) { return } - var mac by + var mac []byte if mac, err = sha256Hmac(auth, cipher, o.nonce); chk.E(err) { return } - ct := make(by, 0, 1+32+len(cipher)+32) + ct := make([]byte, 0, 1+32+len(cipher)+32) ct = append(ct, version) ct = append(ct, o.nonce...) ct = append(ct, cipher...) @@ -85,7 +86,7 @@ func Encrypt(plaintext st, conversationKey by, return } -func Decrypt(b64ciphertextWrapped st, conversationKey by) (plaintext st, err er) { +func Decrypt(b64ciphertextWrapped string, conversationKey []byte) (plaintext string, err error) { cLen := len(b64ciphertextWrapped) if cLen < 132 || cLen > 87472 { err = errorf.E("invalid payload length: %d", cLen) @@ -95,7 +96,7 @@ func Decrypt(b64ciphertextWrapped st, conversationKey by) (plaintext st, err er) err = errorf.E("unknown version") return } - var decoded by + var decoded []byte if decoded, err = base64.StdEncoding.DecodeString(b64ciphertextWrapped); chk.E(err) { return } @@ -109,11 +110,11 @@ func Decrypt(b64ciphertextWrapped st, conversationKey by) (plaintext st, err er) return } nonce, ciphertext, givenMac := decoded[1:33], decoded[33:dLen-32], decoded[dLen-32:] - var enc, cc20nonce, auth by + var enc, cc20nonce, auth []byte if enc, cc20nonce, auth, err = getKeys(conversationKey, nonce); chk.E(err) { return } - var expectedMac by + var expectedMac []byte if expectedMac, err = sha256Hmac(auth, ciphertext, nonce); chk.E(err) { return } @@ -121,51 +122,51 @@ func Decrypt(b64ciphertextWrapped st, conversationKey by) (plaintext st, err er) err = errorf.E("invalid hmac") return } - var padded by + var padded []byte if padded, err = encrypt(enc, cc20nonce, ciphertext); chk.E(err) { return } unpaddedLen := binary.BigEndian.Uint16(padded[0:2]) if unpaddedLen < uint16(MinPlaintextSize) || unpaddedLen > uint16(MaxPlaintextSize) || - len(padded) != 2+calcPadding(no(unpaddedLen)) { + len(padded) != 2+calcPadding(int(unpaddedLen)) { err = errorf.E("invalid padding") return } unpadded := padded[2:][:unpaddedLen] - if len(unpadded) == 0 || len(unpadded) != no(unpaddedLen) { + if len(unpadded) == 0 || len(unpadded) != int(unpaddedLen) { err = errorf.E("invalid padding") return } - plaintext = st(unpadded) + plaintext = string(unpadded) return } -func GenerateConversationKey(pkh, skh st) (ck by, err er) { +func GenerateConversationKey(pkh, skh string) (ck []byte, err error) { if skh >= "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141" || skh == "0000000000000000000000000000000000000000000000000000000000000000" { err = errorf.E("invalid private key: x coordinate %s is not on the secp256k1 curve", skh) return } - var shared by + var shared []byte if shared, err = ComputeSharedSecret(pkh, skh); chk.E(err) { return } - ck = hkdf.Extract(sha256.New, shared, by("nip44-v2")) + ck = hkdf.Extract(sha256.New, shared, []byte("nip44-v2")) return } -func encrypt(key, nonce, message by) (dst by, err er) { +func encrypt(key, nonce, message []byte) (dst []byte, err error) { var cipher *chacha20.Cipher if cipher, err = chacha20.NewUnauthenticatedCipher(key, nonce); chk.E(err) { return } - dst = make(by, len(message)) + dst = make([]byte, len(message)) cipher.XORKeyStream(dst, message) return } -func sha256Hmac(key, ciphertext, nonce by) (h by, err er) { +func sha256Hmac(key, ciphertext, nonce []byte) (h []byte, err error) { if len(nonce) != sha256.Size { err = errorf.E("nonce aad must be 32 bytes") return @@ -177,7 +178,7 @@ func sha256Hmac(key, ciphertext, nonce by) (h by, err er) { return } -func getKeys(conversationKey, nonce by) (enc, cc20nonce, auth by, err er) { +func getKeys(conversationKey, nonce []byte) (enc, cc20nonce, auth []byte, err error) { if len(conversationKey) != 32 { err = errorf.E("conversation key must be 32 bytes") return @@ -187,27 +188,27 @@ func getKeys(conversationKey, nonce by) (enc, cc20nonce, auth by, err er) { return } r := hkdf.Expand(sha256.New, conversationKey, nonce) - enc = make(by, 32) + enc = make([]byte, 32) if _, err = io.ReadFull(r, enc); chk.E(err) { return } - cc20nonce = make(by, 12) + cc20nonce = make([]byte, 12) if _, err = io.ReadFull(r, cc20nonce); chk.E(err) { return } - auth = make(by, 32) + auth = make([]byte, 32) if _, err = io.ReadFull(r, auth); chk.E(err) { return } return } -func calcPadding(sLen no) (l no) { +func calcPadding(sLen int) (l int) { if sLen <= 32 { return 32 } - nextPower := 1 << no(math.Floor(math.Log2(float64(sLen-1)))+1) - chunk := no(math.Max(32, float64(nextPower/8))) - l = chunk * no(math.Floor(float64((sLen-1)/chunk))+1) + nextPower := 1 << int(math.Floor(math.Log2(float64(sLen-1)))+1) + chunk := int(math.Max(32, float64(nextPower/8))) + l = chunk * int(math.Floor(float64((sLen-1)/chunk))+1) return } diff --git a/encryption/nip44_test.go b/encryption/nip44_test.go index f08232e..3f71ea3 100644 --- a/encryption/nip44_test.go +++ b/encryption/nip44_test.go @@ -14,12 +14,12 @@ import ( "realy.lol/sha256" ) -func assertCryptPriv(t *testing.T, sk1, sk2, conversationKey, salt, plaintext, expected st) { +func assertCryptPriv(t *testing.T, sk1, sk2, conversationKey, salt, plaintext, expected string) { var ( - k1, s by - actual, decrypted st - ok bo - err er + k1, s []byte + actual, decrypted string + ok bool + err error ) k1, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for conversation key: %v", err); !ok { @@ -46,11 +46,11 @@ func assertCryptPriv(t *testing.T, sk1, sk2, conversationKey, salt, plaintext, e assert.Equal(t, decrypted, plaintext, "wrong decryption") } -func assertDecryptFail(t *testing.T, conversationKey, plaintext, ciphertext, msg st) { +func assertDecryptFail(t *testing.T, conversationKey, plaintext, ciphertext, msg string) { var ( - k1 by - ok bo - err er + k1 []byte + ok bool + err error ) k1, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for conversation key: %v", err); !ok { @@ -60,17 +60,17 @@ func assertDecryptFail(t *testing.T, conversationKey, plaintext, ciphertext, msg assert.ErrorContains(t, err, msg) } -func assertConversationKeyFail(t *testing.T, priv st, pub st, msg st) { +func assertConversationKeyFail(t *testing.T, priv string, pub string, msg string) { _, err := GenerateConversationKey(pub, priv) assert.ErrorContains(t, err, msg) } -func assertConversationKeyGeneration(t *testing.T, priv, pub, conversationKey st) bo { +func assertConversationKeyGeneration(t *testing.T, priv, pub, conversationKey string) bool { var ( actualConversationKey, - expectedConversationKey by - ok bo - err er + expectedConversationKey []byte + ok bool + err error ) expectedConversationKey, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for conversation key: %v", err); !ok { @@ -87,7 +87,7 @@ func assertConversationKeyGeneration(t *testing.T, priv, pub, conversationKey st return true } -func assertConversationKeyGenerationSec(t *testing.T, sk1, sk2, conversationKey st) bo { +func assertConversationKeyGenerationSec(t *testing.T, sk1, sk2, conversationKey string) bool { pub2, err := keys.GetPublicKeyHex(sk2) if ok := assert.NoErrorf(t, err, "failed to derive pubkey from sk2: %v", err); !ok { return false @@ -95,17 +95,17 @@ func assertConversationKeyGenerationSec(t *testing.T, sk1, sk2, conversationKey return assertConversationKeyGeneration(t, sk1, pub2, conversationKey) } -func assertConversationKeyGenerationPub(t *testing.T, sk, pub, conversationKey st) bo { +func assertConversationKeyGenerationPub(t *testing.T, sk, pub, conversationKey string) bool { return assertConversationKeyGeneration(t, sk, pub, conversationKey) } func assertMessageKeyGeneration(t *testing.T, - conversationKey, salt, chachaKey, chachaSalt, hmacKey st) bo { + conversationKey, salt, chachaKey, chachaSalt, hmacKey string) bool { var ( convKey, convSalt, actualChaChaKey, expectedChaChaKey, actualChaChaNonce, - expectedChaChaNonce, actualHmacKey, expectedHmacKey by - ok bo - err er + expectedChaChaNonce, actualHmacKey, expectedHmacKey []byte + ok bool + err error ) convKey, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for convKey: %v", err); !ok { @@ -144,14 +144,14 @@ func assertMessageKeyGeneration(t *testing.T, return true } -func assertCryptLong(t *testing.T, conversationKey, salt, pattern st, repeat int, - plaintextSha256, payloadSha256 st) { +func assertCryptLong(t *testing.T, conversationKey, salt, pattern string, repeat int, + plaintextSha256, payloadSha256 string) { var ( - convKey, convSalt by - plaintext, actualPlaintextSha256, actualPayload, actualPayloadSha256 st + convKey, convSalt []byte + plaintext, actualPlaintextSha256, actualPayload, actualPayloadSha256 string h hash.Hash - ok bo - err er + ok bool + err error ) convKey, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for convKey: %v", err); !ok { @@ -166,7 +166,7 @@ func assertCryptLong(t *testing.T, conversationKey, salt, pattern st, repeat int plaintext += pattern } h = sha256.New() - h.Write(by(plaintext)) + h.Write([]byte(plaintext)) actualPlaintextSha256 = hex.Enc(h.Sum(nil)) if ok = assert.Equalf(t, plaintextSha256, actualPlaintextSha256, "invalid plaintext sha256 hash: %v", err); !ok { @@ -177,7 +177,7 @@ func assertCryptLong(t *testing.T, conversationKey, salt, pattern st, repeat int return } h.Reset() - h.Write(by(actualPayload)) + h.Write([]byte(actualPayload)) actualPayloadSha256 = hex.Enc(h.Sum(nil)) if ok = assert.Equalf(t, payloadSha256, actualPayloadSha256, "invalid payload sha256 hash: %v", err); !ok { @@ -1142,10 +1142,10 @@ func TestMessageKeyGeneration033(t *testing.T) { func TestMaxLength(t *testing.T) { sk1 := keys.GeneratePrivateKey() sk2 := keys.GeneratePrivateKey() - pub2, _ := keys.GetPublicKeyHex(st(sk2)) - salt := make(by, 32) + pub2, _ := keys.GetPublicKeyHex(string(sk2)) + salt := make([]byte, 32) rand.Read(salt) - conversationKey, _ := GenerateConversationKey(pub2, st(sk1)) + conversationKey, _ := GenerateConversationKey(pub2, string(sk1)) plaintext := strings.Repeat("a", MaxPlaintextSize) encrypted, err := Encrypt(plaintext, conversationKey, WithCustomNonce(salt)) if chk.E(err) { @@ -1153,7 +1153,7 @@ func TestMaxLength(t *testing.T) { } assertCryptPub(t, - st(sk1), + string(sk1), pub2, fmt.Sprintf("%x", conversationKey), fmt.Sprintf("%x", salt), @@ -1162,12 +1162,12 @@ func TestMaxLength(t *testing.T) { ) } -func assertCryptPub(t *testing.T, sk1, pub2, conversationKey, salt, plaintext, expected st) { +func assertCryptPub(t *testing.T, sk1, pub2, conversationKey, salt, plaintext, expected string) { var ( - k1, s by - actual, decrypted st - ok bo - err er + k1, s []byte + actual, decrypted string + ok bool + err error ) k1, err = hex.Dec(conversationKey) if ok = assert.NoErrorf(t, err, "hex decode failed for conversation key: %v", err); !ok { diff --git a/encryption/util.go b/encryption/util.go index b3ea6f0..1db0834 100644 --- a/encryption/util.go +++ b/encryption/util.go @@ -1,22 +1,9 @@ package encryption import ( - "bytes" - - "realy.lol/context" "realy.lol/lol" ) -type ( - bo = bool - by = []byte - st = string - er = error - no = int - cx = context.T -) - var ( log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf - equals = bytes.Equal )