moved everything into pkg/

This commit is contained in:
2025-07-17 13:18:55 +01:00
parent affd6c1ebc
commit fc68bcf3cb
466 changed files with 1481 additions and 2119 deletions

4
.gitignore vendored
View File

@@ -64,7 +64,7 @@ node_modules/**
!.gitmodules
!*.txt
!*.sum
!version
!pkg/version
!*.service
!*.benc
!*.png
@@ -90,7 +90,7 @@ node_modules/**
/blocklist.json
/gui/gui/main.wasm
/gui/gui/index.html
database/testrealy
pkg/database/testrealy
/.idea/workspace.xml
/.idea/dictionaries/project.xml
/.idea/shelf/Add_tombstone_handling__enhance_event_ID_logic__update_imports.xml

View File

@@ -1,9 +0,0 @@
package base58_test
import (
"orly.dev/utils/lol"
)
var (
log, chk, errorf = lol.Main.Log, lol.Main.Check, lol.Main.Errorf
)

View File

@@ -1,39 +0,0 @@
package database
import (
"bytes"
"github.com/dgraph-io/badger/v4"
"orly.dev/database/indexes"
"orly.dev/database/indexes/types"
"orly.dev/encoders/codecbuf"
"orly.dev/encoders/event"
"orly.dev/utils/chk"
)
func (d *D) FetchEventBySerial(ser *types.Uint40) (ev *event.E, err error) {
if err = d.View(
func(txn *badger.Txn) (err error) {
buf := codecbuf.Get()
defer codecbuf.Put(buf)
if err = indexes.EventEnc(ser).MarshalWrite(buf); chk.E(err) {
return
}
var item *badger.Item
if item, err = txn.Get(buf.Bytes()); chk.E(err) {
return
}
var v []byte
if v, err = item.ValueCopy(nil); chk.E(err) {
return
}
ev = new(event.E)
if err = ev.UnmarshalBinary(bytes.NewBuffer(v)); chk.E(err) {
return
}
return
},
); err != nil {
return
}
return
}

View File

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

View File

@@ -1,218 +0,0 @@
package json
import (
"bytes"
"fmt"
"orly.dev/utils/chk"
"orly.dev/encoders/hex"
)
func ExampleBool_Marshal() {
var b []byte
bt := &Bool{true}
b = bt.Marshal(b)
fmt.Printf("%s\n", b)
bt2 := &Bool{}
rem, err := bt2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", bt2.V == true)
b = b[:0]
bf := &Bool{} // implicit initialized bool is false
b = bf.Marshal(b)
fmt.Printf("%s\n", b)
fmt.Printf("%v\n", bf.V == false)
// Output:
// true
// true
// false
// true
}
func ExampleUnsigned_Marshal() {
var b []byte
u := &Unsigned{}
b = u.Marshal(b)
fmt.Printf("%s\n", b)
u2 := &Unsigned{}
rem, err := u2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", u2.V == 0)
u.V = 69420
b = b[:0]
b = u.Marshal(b)
fmt.Printf("%s\n", b)
rem, err = u2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", u2.V == 69420)
// Output:
// 0
// true
// 69420
// true
}
func ExampleSigned_Marshal() {
var b []byte
s := &Signed{}
b = s.Marshal(b)
fmt.Printf("%s\n", b)
s2 := &Signed{}
rem, err := s2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", s2.V == 0)
s.V = 69420
b = b[:0]
b = s.Marshal(b)
fmt.Printf("%s\n", b)
rem, err = s2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", s2.V == s.V)
s.V *= -69420
b = b[:0]
b = s.Marshal(b)
fmt.Printf("%s\n", b)
rem, err = s2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", s2.V == s.V)
// Output:
// 0
// true
// 69420
// true
// -4819136400
// true
}
func ExampleString_Marshal() {
var b []byte
const ex = `test with
newlines and hidden tab and spaces at the end `
s := NewString(ex)
b = s.Marshal(b)
fmt.Printf("%s\n", b)
s2 := &String{}
rem, err := s2.Unmarshal(b)
if err != nil || len(rem) != 0 {
return
}
fmt.Printf("%v\n", bytes.Equal(s2.V, []byte(ex)))
// Output:
// "test with\n\t\nnewlines and hidden tab and spaces at the end "
// true
}
func ExampleBech32_Marshal() {
const (
hrp = "herp"
hexVal = "00deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef"
)
bin, err := hex.Dec(hexVal)
if err != nil {
return
}
b32 := &Bech32{[]byte(hrp), bin}
b := b32.Marshal(nil)
fmt.Printf("%s\n", b)
b33 := &Bech32{HRP: []byte(hrp)}
var rem []byte
rem, err = b33.Unmarshal(b)
if chk.E(err) || len(rem) != 0 {
return
}
fmt.Printf("hrp: %s\ndata: %0x\n", b33.HRP, b33.V)
fmt.Printf("%v\n", bytes.Equal(bin, b33.V))
// Output:
// "herp1qr02m0h0etlqzg69v7y6hn00qr02m0h0etlqzg69v7y6hn00jujvlj"
// hrp: herp
// data: 00deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef
// true
}
func ExampleHex_Marshal() {
const (
hexVal = "deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef"
)
bin, err := hex.Dec(hexVal)
if err != nil {
return
}
h := &Hex{bin}
b := h.Marshal(nil)
fmt.Printf("%s\n", b)
h2 := &Hex{}
var rem []byte
rem, err = h2.Unmarshal(b)
if chk.E(err) || len(rem) != 0 {
fmt.Printf("%s\n%s", err.Error(), rem)
return
}
fmt.Printf("data: %0x\n", h2.V)
fmt.Printf("%v\n", bytes.Equal(bin, h2.V))
// Output:
// "deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef"
// data: deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef
// true
}
func ExampleBase64_Marshal() {
const (
hexVal = "deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef00"
)
bin, err := hex.Dec(hexVal)
if err != nil {
return
}
b1 := &Base64{bin}
var b []byte
b = b1.Marshal(nil)
fmt.Printf("%s\n", b)
b2 := &Base64{}
var rem []byte
rem, err = b2.Unmarshal(b)
if chk.E(err) || len(rem) != 0 {
fmt.Printf("%s\n%s", err.Error(), rem)
return
}
fmt.Printf("data: %0x\n", b2.V)
fmt.Printf("%v\n", bytes.Equal(bin, b2.V))
// Output:
// "3q2+78r+ASNFZ4mrze8A3q2+78r+ASNFZ4mrze8A"
// data: deadbeefcafe0123456789abcdef00deadbeefcafe0123456789abcdef00
// true
}
func ExampleKeyValue_Marshal() {
const (
// deliberately put whitespace here to make sure it parses. even garbage will parse, but
// we aren't going to bother, mainly whitespace needs to be allowed.
keyVal = `"key" :
"value"`
)
kv := &KeyValue{Value: &String{}}
rem, err := kv.Unmarshal([]byte(keyVal))
if chk.E(err) || len(rem) != 0 {
fmt.Printf("%s\n'%s'", err.Error(), rem)
return
}
kv2 := &KeyValue{[]byte("key"), &String{[]byte("value")}}
var b, b2 []byte
b = kv.Marshal(b)
b2 = kv2.Marshal(b2)
fmt.Printf("%s\n%s\n%v\n", b, b2, bytes.Equal(b, b2))
// Output:
// "key":"value"
// "key":"value"
// true
}

View File

@@ -1,36 +0,0 @@
package json
import (
"orly.dev/encoders/text"
"orly.dev/utils/chk"
)
// String is a regular string. Must be escaped as per nip-01. Bytes stored in it
// are not escaped, only must be escaped to output JSON.
//
// Again like the other types, create a new String with:
//
// str := json.String{}
//
// There is also a convenience NewString function that generically automatically
// converts actual golang strings to save the caller from doing so.
type String struct{ V []byte }
// NewString creates a new String from a string or byte string.
func NewString[V ~string | ~[]byte](s V) *String { return &String{[]byte(s)} }
// Marshal a String into a quoted byte string.
func (s *String) Marshal(dst []byte) (b []byte) {
b = text.AppendQuote(dst, s.V, text.NostrEscape)
return
}
// Unmarshal from a quoted JSON string into a String.
func (s *String) Unmarshal(dst []byte) (rem []byte, err error) {
var c []byte
if c, rem, err = text.UnmarshalQuoted(dst); chk.E(err) {
return
}
s.V = c
return
}

27
main.go
View File

@@ -8,19 +8,18 @@ import (
"github.com/pkg/profile"
"net/http"
_ "net/http/pprof"
"orly.dev/app/relay"
"orly.dev/app/relay/options"
"orly.dev/utils/chk"
"orly.dev/utils/interrupt"
"orly.dev/utils/log"
"orly.dev/version"
app2 "orly.dev/pkg/app"
"orly.dev/pkg/app/config"
"orly.dev/pkg/app/relay"
"orly.dev/pkg/app/relay/options"
"orly.dev/pkg/database"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/interrupt"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/utils/lol"
"orly.dev/pkg/version"
"os"
"orly.dev/app"
"orly.dev/app/config"
"orly.dev/database"
"orly.dev/utils/context"
"orly.dev/utils/lol"
)
func main() {
@@ -55,8 +54,8 @@ func main() {
if chk.E(err) {
os.Exit(1)
}
r := &app.Relay{C: cfg, Store: storage}
go app.MonitorResources(c)
r := &app2.Relay{C: cfg, Store: storage}
go app2.MonitorResources(c)
var server *relay.Server
serverParams := &relay.ServerParams{
Ctx: c,

View File

@@ -5,11 +5,12 @@ package config
import (
"fmt"
"io"
"orly.dev/utils/chk"
env2 "orly.dev/utils/env"
"orly.dev/utils/log"
"orly.dev/utils/lol"
"orly.dev/version"
"orly.dev/pkg/utils/apputil"
"orly.dev/pkg/utils/chk"
env2 "orly.dev/pkg/utils/env"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/utils/lol"
"orly.dev/pkg/version"
"os"
"path/filepath"
"reflect"
@@ -19,8 +20,6 @@ import (
"github.com/adrg/xdg"
"go-simpler.org/env"
"orly.dev/utils/apputil"
)
// C is the configuration for the relay. These are read from the environment if

View File

@@ -3,14 +3,13 @@ package app
import (
"net/http"
"orly.dev/pkg/app/config"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/encoders/filter"
"orly.dev/pkg/encoders/filters"
"orly.dev/pkg/interfaces/store"
"orly.dev/pkg/utils/context"
"sync"
"orly.dev/app/config"
"orly.dev/encoders/event"
"orly.dev/encoders/filter"
"orly.dev/encoders/filters"
"orly.dev/interfaces/store"
"orly.dev/utils/context"
)
type List map[string]struct{}

View File

@@ -2,8 +2,8 @@ package relay
import (
"net/http"
"orly.dev/encoders/event"
"orly.dev/utils/context"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/utils/context"
)
func (s *Server) AcceptEvent(

View File

@@ -2,8 +2,8 @@ package relay
import (
"net/http"
"orly.dev/encoders/filters"
"orly.dev/utils/context"
"orly.dev/pkg/encoders/filters"
"orly.dev/pkg/utils/context"
)
func (s *Server) AcceptReq(

View File

@@ -3,14 +3,13 @@ package relay
import (
"errors"
"net/http"
"orly.dev/interfaces/relay"
"orly.dev/utils/normalize"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/interfaces/relay"
"orly.dev/pkg/interfaces/store"
"orly.dev/pkg/protocol/socketapi"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/normalize"
"strings"
"orly.dev/encoders/event"
"orly.dev/interfaces/store"
"orly.dev/protocol/socketapi"
"orly.dev/utils/context"
)
func (s *Server) AddEvent(

View File

@@ -2,9 +2,9 @@ package relay
import (
"net/http"
"orly.dev/utils/chk"
"orly.dev/utils/log"
"orly.dev/utils/lol"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/utils/lol"
"strconv"
"strings"
)

View File

@@ -3,13 +3,12 @@ package relay
import (
"encoding/json"
"net/http"
"orly.dev/interfaces/relay"
"orly.dev/utils/chk"
"orly.dev/utils/log"
"orly.dev/version"
"orly.dev/pkg/interfaces/relay"
"orly.dev/pkg/protocol/relayinfo"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/version"
"sort"
"orly.dev/protocol/relayinfo"
)
func (s *Server) handleRelayInfo(w http.ResponseWriter, r *http.Request) {

View File

@@ -2,8 +2,7 @@ package relay
import (
"net/http"
"orly.dev/protocol/socketapi"
"orly.dev/pkg/protocol/socketapi"
)
func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) {

View File

@@ -6,7 +6,7 @@
package options
import (
"orly.dev/encoders/event"
"orly.dev/pkg/encoders/event"
)
type SkipEventFunc func(*event.E) bool

View File

@@ -4,8 +4,8 @@
package publish
import (
"orly.dev/encoders/event"
"orly.dev/interfaces/publisher"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/interfaces/publisher"
)
// S is the control structure for the subscription management scheme.

View File

@@ -1,11 +1,11 @@
package relay
import (
"orly.dev/app/relay/publish"
"orly.dev/interfaces/relay"
"orly.dev/interfaces/server"
"orly.dev/interfaces/store"
"orly.dev/utils/context"
"orly.dev/pkg/app/relay/publish"
"orly.dev/pkg/interfaces/relay"
"orly.dev/pkg/interfaces/server"
"orly.dev/pkg/interfaces/store"
"orly.dev/pkg/utils/context"
)
func (s *Server) Storage() store.I { return s.relay.Storage() }

View File

@@ -4,18 +4,17 @@ import (
"bytes"
"errors"
"fmt"
"orly.dev/encoders/tags"
"orly.dev/utils/chk"
"orly.dev/utils/errorf"
"orly.dev/utils/log"
"orly.dev/utils/normalize"
"orly.dev/encoders/event"
"orly.dev/encoders/filter"
"orly.dev/encoders/kinds"
"orly.dev/encoders/tag"
"orly.dev/interfaces/store"
"orly.dev/utils/context"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/encoders/filter"
"orly.dev/pkg/encoders/kinds"
"orly.dev/pkg/encoders/tag"
"orly.dev/pkg/encoders/tags"
"orly.dev/pkg/interfaces/store"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/errorf"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/utils/normalize"
)
// Publish processes and saves an event based on its type and rules.

View File

@@ -6,21 +6,20 @@ import (
"fmt"
"net"
"net/http"
"orly.dev/app/config"
"orly.dev/app/relay/helpers"
"orly.dev/app/relay/options"
"orly.dev/app/relay/publish"
"orly.dev/interfaces/relay"
"orly.dev/protocol/servemux"
"orly.dev/utils/chk"
"orly.dev/utils/log"
"orly.dev/pkg/app/config"
"orly.dev/pkg/app/relay/helpers"
"orly.dev/pkg/app/relay/options"
"orly.dev/pkg/app/relay/publish"
"orly.dev/pkg/interfaces/relay"
"orly.dev/pkg/protocol/servemux"
"orly.dev/pkg/protocol/socketapi"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/log"
"strconv"
"time"
"github.com/rs/cors"
"orly.dev/protocol/socketapi"
"orly.dev/utils/context"
)
type Server struct {

View File

@@ -3,14 +3,13 @@ package relay
import (
"io"
"net/http"
"orly.dev/pkg/encoders/event"
"orly.dev/pkg/encoders/eventid"
"orly.dev/pkg/encoders/filter"
"orly.dev/pkg/interfaces/store"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/units"
"testing"
"orly.dev/encoders/event"
"orly.dev/encoders/eventid"
"orly.dev/encoders/filter"
"orly.dev/interfaces/store"
"orly.dev/utils/context"
"orly.dev/utils/units"
)
func startTestRelay(c context.T, t *testing.T, tr *testRelay) *Server {

View File

@@ -1,12 +1,11 @@
package app
import (
"orly.dev/utils/log"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/log"
"os"
"runtime"
"time"
"orly.dev/utils/context"
)
func MonitorResources(c context.T) {

View File

@@ -14,8 +14,14 @@ import (
"net/http"
"net/http/httputil"
"net/url"
"orly.dev/utils/chk"
"orly.dev/utils/log"
"orly.dev/pkg/cmd/lerproxy/buf"
"orly.dev/pkg/cmd/lerproxy/hsts"
"orly.dev/pkg/cmd/lerproxy/reverse"
"orly.dev/pkg/cmd/lerproxy/tcpkeepalive"
"orly.dev/pkg/cmd/lerproxy/util"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/context"
"orly.dev/pkg/utils/log"
"os"
"os/signal"
"path/filepath"
@@ -27,13 +33,6 @@ import (
"github.com/alexflint/go-arg"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/sync/errgroup"
"orly.dev/cmd/lerproxy/buf"
"orly.dev/cmd/lerproxy/hsts"
"orly.dev/cmd/lerproxy/reverse"
"orly.dev/cmd/lerproxy/tcpkeepalive"
"orly.dev/cmd/lerproxy/util"
"orly.dev/utils/context"
)
type runArgs struct {

View File

@@ -6,9 +6,8 @@ import (
"net/http"
"net/http/httputil"
"net/url"
"orly.dev/utils/log"
"orly.dev/cmd/lerproxy/util"
"orly.dev/pkg/cmd/lerproxy/util"
"orly.dev/pkg/utils/log"
)
// NewSingleHostReverseProxy is a copy of httputil.NewSingleHostReverseProxy

View File

@@ -4,10 +4,9 @@ package tcpkeepalive
import (
"net"
"orly.dev/utils/chk"
"orly.dev/pkg/cmd/lerproxy/timeout"
"orly.dev/pkg/utils/chk"
"time"
"orly.dev/cmd/lerproxy/timeout"
)
// Period can be changed prior to opening a Listener to alter its'

View File

@@ -4,7 +4,7 @@ package timeout
import (
"net"
"orly.dev/utils/chk"
"orly.dev/pkg/utils/chk"
"time"
)

View File

@@ -3,16 +3,15 @@ package main
import (
"encoding/base64"
"fmt"
"orly.dev/crypto/p256k"
"orly.dev/encoders/bech32encoding"
"orly.dev/utils/chk"
"orly.dev/utils/errorf"
"orly.dev/utils/log"
"orly.dev/pkg/crypto/p256k"
"orly.dev/pkg/encoders/bech32encoding"
"orly.dev/pkg/interfaces/signer"
"orly.dev/pkg/protocol/httpauth"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/errorf"
"orly.dev/pkg/utils/log"
"os"
"time"
"orly.dev/interfaces/signer"
"orly.dev/protocol/httpauth"
)
const secEnv = "NOSTR_SECRET_KEY"

View File

@@ -8,18 +8,17 @@ import (
"io"
"net/http"
"net/url"
"orly.dev/crypto/p256k"
"orly.dev/crypto/sha256"
"orly.dev/encoders/bech32encoding"
"orly.dev/utils/chk"
"orly.dev/utils/errorf"
"orly.dev/utils/log"
realy_lol "orly.dev/version"
"orly.dev/pkg/crypto/p256k"
"orly.dev/pkg/crypto/sha256"
"orly.dev/pkg/encoders/bech32encoding"
"orly.dev/pkg/encoders/hex"
"orly.dev/pkg/interfaces/signer"
"orly.dev/pkg/protocol/httpauth"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/errorf"
"orly.dev/pkg/utils/log"
realy_lol "orly.dev/pkg/version"
"os"
"orly.dev/encoders/hex"
"orly.dev/interfaces/signer"
"orly.dev/protocol/httpauth"
)
const secEnv = "NOSTR_SECRET_KEY"

View File

@@ -6,13 +6,15 @@ import (
"bytes"
"encoding/hex"
"fmt"
"orly.dev/crypto/ec/bech32"
"orly.dev/crypto/ec/schnorr"
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/encoders/bech32encoding"
"orly.dev/utils/chk"
"orly.dev/utils/interrupt"
"orly.dev/utils/log"
"orly.dev/pkg/crypto/ec/bech32"
"orly.dev/pkg/crypto/ec/schnorr"
"orly.dev/pkg/crypto/ec/secp256k1"
"orly.dev/pkg/encoders/bech32encoding"
"orly.dev/pkg/utils/atomic"
"orly.dev/pkg/utils/chk"
"orly.dev/pkg/utils/interrupt"
"orly.dev/pkg/utils/log"
"orly.dev/pkg/utils/qu"
"os"
"runtime"
"strings"
@@ -20,9 +22,6 @@ import (
"time"
"github.com/alexflint/go-arg"
"orly.dev/utils/atomic"
"orly.dev/utils/qu"
)
var prefix = append(bech32encoding.PubHRP, '1')
@@ -34,9 +33,9 @@ const (
)
type Result struct {
sec *secp256k2.SecretKey
sec *secp256k1.SecretKey
npub []byte
pub *secp256k2.PublicKey
pub *secp256k1.PublicKey
}
var args struct {
@@ -219,11 +218,11 @@ out:
// GenKeyPair creates a fresh new key pair using the entropy source used by
// crypto/rand (ie, /dev/random on posix systems).
func GenKeyPair() (
sec *secp256k2.SecretKey,
pub *secp256k2.PublicKey, err error,
sec *secp256k1.SecretKey,
pub *secp256k1.PublicKey, err error,
) {
sec, err = secp256k2.GenerateSecretKey()
sec, err = secp256k1.GenerateSecretKey()
if err != nil {
err = fmt.Errorf("error generating key: %s", err)
return

View File

@@ -7,7 +7,7 @@ package base58_test
import (
"bytes"
"encoding/hex"
"orly.dev/crypto/ec/base58"
"orly.dev/pkg/crypto/ec/base58"
"testing"
)

View File

@@ -6,7 +6,7 @@ package base58_test
import (
"bytes"
"orly.dev/crypto/ec/base58"
"orly.dev/pkg/crypto/ec/base58"
"testing"
)

View File

@@ -6,7 +6,7 @@ package base58
import (
"errors"
"orly.dev/crypto/sha256"
"orly.dev/pkg/crypto/sha256"
)
// ErrChecksum indicates that the checksum of a check-encoded string does not verify against

View File

@@ -5,7 +5,7 @@
package base58_test
import (
"orly.dev/crypto/ec/base58"
"orly.dev/pkg/crypto/ec/base58"
"testing"
)

View File

@@ -6,14 +6,14 @@ package base58_test
import (
"fmt"
base59 "orly.dev/crypto/ec/base58"
"orly.dev/pkg/crypto/ec/base58"
)
// This example demonstrates how to decode modified base58 encoded data.
func ExampleDecode() {
// Decode example modified base58 encoded data.
encoded := "25JnwSn7XKfNQ"
decoded := base59.Decode(encoded)
decoded := base58.Decode(encoded)
// Show the decoded data.
fmt.Println("Decoded Data:", string(decoded))
@@ -27,7 +27,7 @@ func ExampleDecode() {
func ExampleEncode() {
// Encode example data with the modified base58 encoding scheme.
data := []byte("Test data")
encoded := base59.Encode(data)
encoded := base58.Encode(data)
// Show the encoded data.
fmt.Println("Encoded Data:", encoded)
@@ -40,7 +40,7 @@ func ExampleEncode() {
func ExampleCheckDecode() {
// Decode an example Base58Check encoded data.
encoded := "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
decoded, version, err := base59.CheckDecode(encoded)
decoded, version, err := base58.CheckDecode(encoded)
if err != nil {
fmt.Println(err)
return
@@ -60,7 +60,7 @@ func ExampleCheckDecode() {
func ExampleCheckEncode() {
// Encode example data with the Base58Check encoding scheme.
data := []byte("Test data")
encoded := base59.CheckEncode(data, 0)
encoded := base58.CheckEncode(data, 0)
// Show the encoded data.
fmt.Println("Encoded Data:", encoded)

View File

@@ -52,7 +52,7 @@ func TestBech32(t *testing.T) {
{
"split1cheo2y9e2w",
ErrNonCharsetChar('o'),
}, // invalid character (o) in data part
}, // invalid character (o) in data part
{"split1a2y9w", ErrInvalidSeparatorIndex(5)}, // too short data part
{
"1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",

View File

@@ -6,10 +6,9 @@ package btcec
import (
"math/big"
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
"orly.dev/pkg/encoders/hex"
"testing"
"orly.dev/encoders/hex"
)
// setHex decodes the passed big-endian hex string into the internal field value

View File

@@ -20,31 +20,31 @@ package btcec
// reverse the transform than to operate in affine coordinates.
import (
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// KoblitzCurve provides an implementation for secp256k1 that fits the ECC
// Curve interface from crypto/elliptic.
type KoblitzCurve = secp256k2.KoblitzCurve
type KoblitzCurve = secp256k1.KoblitzCurve
// S256 returns a Curve which implements secp256k1.
func S256() *KoblitzCurve {
return secp256k2.S256()
return secp256k1.S256()
}
// CurveParams contains the parameters for the secp256k1 curve.
type CurveParams = secp256k2.CurveParams
type CurveParams = secp256k1.CurveParams
// Params returns the secp256k1 curve parameters for convenience.
func Params() *CurveParams {
return secp256k2.Params()
return secp256k1.Params()
}
// Generator returns the public key at the Generator Point.
func Generator() *PublicKey {
var (
result JacobianPoint
k secp256k2.ModNScalar
k secp256k1.ModNScalar
)
k.SetInt(1)
ScalarBaseMultNonConst(&k, &result)

View File

@@ -2,7 +2,7 @@ package chaincfg
import (
"fmt"
"orly.dev/crypto/ec/wire"
"orly.dev/pkg/crypto/ec/wire"
"time"
)

View File

@@ -1,19 +1,19 @@
package chaincfg
import (
"orly.dev/crypto/ec/chainhash"
wire2 "orly.dev/crypto/ec/wire"
"orly.dev/pkg/crypto/ec/chainhash"
"orly.dev/pkg/crypto/ec/wire"
"time"
)
var (
// genesisCoinbaseTx is the coinbase transaction for the genesis blocks for
// the main network, regression test network, and test network (version 3).
genesisCoinbaseTx = wire2.MsgTx{
genesisCoinbaseTx = wire.MsgTx{
Version: 1,
TxIn: []*wire2.TxIn{
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire2.OutPoint{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
},
@@ -41,7 +41,7 @@ var (
Sequence: 0xffffffff,
},
},
TxOut: []*wire2.TxOut{
TxOut: []*wire.TxOut{
{
Value: 0x12a05f200,
PkScript: []byte{
@@ -92,8 +92,8 @@ var (
// genesisBlock defines
// genesisBlock defines the genesis block of the block chain which serves as the
// public transaction ledger for the main network.
genesisBlock = wire2.MsgBlock{
Header: wire2.BlockHeader{
genesisBlock = wire.MsgBlock{
Header: wire.BlockHeader{
Version: 1,
PrevBlock: chainhash.Hash{}, // 0000000000000000000000000000000000000000000000000000000000000000
MerkleRoot: genesisMerkleRoot, // 4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
@@ -104,6 +104,6 @@ var (
Bits: 0x1d00ffff, // 486604799 [00000000ffff0000000000000000000000000000000000000000000000000000]
Nonce: 0x7c2bac1d, // 2083236893
},
Transactions: []*wire2.MsgTx{&genesisCoinbaseTx},
Transactions: []*wire.MsgTx{&genesisCoinbaseTx},
}
)

View File

@@ -3,8 +3,8 @@ package chaincfg
import (
"math/big"
"orly.dev/crypto/ec/chainhash"
wire2 "orly.dev/crypto/ec/wire"
"orly.dev/pkg/crypto/ec/chainhash"
"orly.dev/pkg/crypto/ec/wire"
"time"
)
@@ -113,7 +113,7 @@ type Params struct {
Name string
// Net defines the magic bytes used to identify the network.
Net wire2.BitcoinNet
Net wire.BitcoinNet
// DefaultPort defines the default peer-to-peer port for the network.
DefaultPort string
@@ -123,7 +123,7 @@ type Params struct {
DNSSeeds []DNSSeed
// GenesisBlock defines the first block of the chain.
GenesisBlock *wire2.MsgBlock
GenesisBlock *wire.MsgBlock
// GenesisHash is the starting block hash.
GenesisHash *chainhash.Hash
@@ -231,7 +231,7 @@ type Params struct {
// MainNetParams defines the network parameters for the main Bitcoin network.
var MainNetParams = Params{
Name: "mainnet",
Net: wire2.MainNet,
Net: wire.MainNet,
DefaultPort: "8333",
DNSSeeds: []DNSSeed{
{"seed.bitcoin.sipa.be", true},

View File

@@ -8,9 +8,8 @@ package chainhash
import (
"encoding/json"
"fmt"
"orly.dev/crypto/sha256"
"orly.dev/encoders/hex"
"orly.dev/pkg/crypto/sha256"
"orly.dev/pkg/encoders/hex"
)
const (

View File

@@ -6,7 +6,7 @@
package chainhash
import (
"orly.dev/crypto/sha256"
"orly.dev/pkg/crypto/sha256"
)
// HashB calculates hash(b) and returns the resulting bytes.

View File

@@ -5,7 +5,7 @@
package btcec
import (
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// GenerateSharedSecret generates a shared secret based on a secret key and a

View File

@@ -5,12 +5,12 @@ package btcec
import (
"fmt"
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// JacobianPoint is an element of the group formed by the secp256k1 curve in
// Jacobian projective coordinates and thus represents a point on the curve.
type JacobianPoint = secp256k2.JacobianPoint
type JacobianPoint = secp256k1.JacobianPoint
// infinityPoint is the jacobian representation of the point at infinity.
var infinityPoint JacobianPoint
@@ -18,13 +18,13 @@ var infinityPoint JacobianPoint
// MakeJacobianPoint returns a Jacobian point with the provided X, Y, and Z
// coordinates.
func MakeJacobianPoint(x, y, z *FieldVal) JacobianPoint {
return secp256k2.MakeJacobianPoint(x, y, z)
return secp256k1.MakeJacobianPoint(x, y, z)
}
// AddNonConst adds the passed Jacobian points together and stores the result
// in the provided result param in *non-constant* time.
func AddNonConst(p1, p2, result *JacobianPoint) {
secp256k2.AddNonConst(p1, p2, result)
secp256k1.AddNonConst(p1, p2, result)
}
// DecompressY attempts to calculate the Y coordinate for the given X
@@ -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 bool, resultY *FieldVal) bool {
return secp256k2.DecompressY(x, odd, resultY)
return secp256k1.DecompressY(x, odd, resultY)
}
// DoubleNonConst doubles the passed Jacobian point and stores the result in
@@ -44,7 +44,7 @@ func DecompressY(x *FieldVal, odd bool, resultY *FieldVal) bool {
// NOTE: The point must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func DoubleNonConst(p, result *JacobianPoint) {
secp256k2.DoubleNonConst(p, result)
secp256k1.DoubleNonConst(p, result)
}
// ScalarBaseMultNonConst multiplies k*G where G is the base point of the group
@@ -53,7 +53,7 @@ func DoubleNonConst(p, result *JacobianPoint) {
//
// NOTE: The resulting point will be normalized.
func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {
secp256k2.ScalarBaseMultNonConst(k, result)
secp256k1.ScalarBaseMultNonConst(k, result)
}
// ScalarMultNonConst multiplies k*P where k is a big endian integer modulo the
@@ -63,7 +63,7 @@ func ScalarBaseMultNonConst(k *ModNScalar, result *JacobianPoint) {
// NOTE: The point must be normalized for this function to return the correct
// result. The resulting point will be normalized.
func ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) {
secp256k2.ScalarMultNonConst(k, point, result)
secp256k1.ScalarMultNonConst(k, point, result)
}
// ParseJacobian parses a byte slice point as a secp256k1.Publickey and returns the
@@ -76,12 +76,12 @@ func ParseJacobian(point []byte) (JacobianPoint, error) {
"invalid nonce: invalid length: %v",
len(point),
)
return JacobianPoint{}, makeError(secp256k2.ErrPubKeyInvalidLen, str)
return JacobianPoint{}, makeError(secp256k1.ErrPubKeyInvalidLen, str)
}
if point[0] == 0x00 {
return infinityPoint, nil
}
noncePk, err := secp256k2.ParsePubKey(point)
noncePk, err := secp256k1.ParsePubKey(point)
if err != nil {
return JacobianPoint{}, err
}

View File

@@ -6,22 +6,21 @@
package ecdsa
import (
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
"orly.dev/pkg/encoders/hex"
"testing"
"orly.dev/encoders/hex"
)
// hexToModNScalar converts the passed hex string into a ModNScalar and will
// 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 string) *secp256k2.ModNScalar {
func hexToModNScalar(s string) *secp256k1.ModNScalar {
b, err := hex.Dec(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
var scalar secp256k2.ModNScalar
var scalar secp256k1.ModNScalar
if overflow := scalar.SetByteSlice(b); overflow {
panic("hex in source file overflows mod N scalar: " + s)
}
@@ -32,12 +31,12 @@ func hexToModNScalar(s string) *secp256k2.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 string) *secp256k2.FieldVal {
func hexToFieldVal(s string) *secp256k1.FieldVal {
b, err := hex.Dec(s)
if err != nil {
panic("invalid hex in source file: " + s)
}
var f secp256k2.FieldVal
var f secp256k1.FieldVal
if overflow := f.SetByteSlice(b); overflow {
panic("hex in source file overflows mod P: " + s)
}
@@ -49,7 +48,7 @@ func hexToFieldVal(s string) *secp256k2.FieldVal {
func BenchmarkSigVerify(b *testing.B) {
// Randomly generated keypair.
// Secret key: 9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d
pubKey := secp256k2.NewPublicKey(
pubKey := secp256k1.NewPublicKey(
hexToFieldVal("d2e670a19c6d753d1a6d8b20bd045df8a08fb162cf508956c31268c6d81ffdab"),
hexToFieldVal("ab65528eefbb8057aa85d597258a3fbd481a24633bc9b47a9aa045c91371de52"),
)
@@ -74,7 +73,7 @@ func BenchmarkSigVerify(b *testing.B) {
func BenchmarkSign(b *testing.B) {
// Randomly generated keypair.
d := hexToModNScalar("9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d")
secKey := secp256k2.NewSecretKey(d)
secKey := secp256k1.NewSecretKey(d)
// blake256 of by{0x01, 0x02, 0x03, 0x04}.
msgHash := hexToBytes("c301ba9de5d6053caad9f5eb46523f007702add2c62fa39de03146a36b8026b7")
b.ReportAllocs()
@@ -114,9 +113,9 @@ func BenchmarkNonceRFC6979(b *testing.B) {
msgHash := hexToBytes("c301ba9de5d6053caad9f5eb46523f007702add2c62fa39de03146a36b8026b7")
b.ReportAllocs()
b.ResetTimer()
var noElideNonce *secp256k2.ModNScalar
var noElideNonce *secp256k1.ModNScalar
for i := 0; i < b.N; i++ {
noElideNonce = secp256k2.NonceRFC6979(secKey, msgHash, nil, nil, 0)
noElideNonce = secp256k1.NonceRFC6979(secKey, msgHash, nil, nil, 0)
}
_ = noElideNonce
}
@@ -125,7 +124,7 @@ func BenchmarkNonceRFC6979(b *testing.B) {
// signature for a message.
func BenchmarkSignCompact(b *testing.B) {
d := hexToModNScalar("9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d")
secKey := secp256k2.NewSecretKey(d)
secKey := secp256k1.NewSecretKey(d)
// blake256 of by{0x01, 0x02, 0x03, 0x04}.
msgHash := hexToBytes("c301ba9de5d6053caad9f5eb46523f007702add2c62fa39de03146a36b8026b7")
b.ReportAllocs()
@@ -139,7 +138,7 @@ func BenchmarkSignCompact(b *testing.B) {
// given a compact signature and message.
func BenchmarkRecoverCompact(b *testing.B) {
// Secret key: 9e0699c91ca1e3b7e3c9ba71eb71c89890872be97576010fe593fbf3fd57e66d
wantPubKey := secp256k2.NewPublicKey(
wantPubKey := secp256k1.NewPublicKey(
hexToFieldVal("d2e670a19c6d753d1a6d8b20bd045df8a08fb162cf508956c31268c6d81ffdab"),
hexToFieldVal("ab65528eefbb8057aa85d597258a3fbd481a24633bc9b47a9aa045c91371de52"),
)

View File

@@ -7,7 +7,7 @@ package ecdsa
import (
"fmt"
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// References:
@@ -27,9 +27,9 @@ var (
// orderAsFieldVal is the order of the secp256k1 curve group stored as a
// field value. It is provided here to avoid the need to create it multiple
// times.
orderAsFieldVal = func() secp256k2.FieldVal {
var f secp256k2.FieldVal
f.SetByteSlice(secp256k2.Params().N.Bytes())
orderAsFieldVal = func() secp256k1.FieldVal {
var f secp256k1.FieldVal
f.SetByteSlice(secp256k1.Params().N.Bytes())
return f
}()
)
@@ -47,12 +47,12 @@ const (
// Signature is a type representing an ECDSA signature.
type Signature struct {
r secp256k2.ModNScalar
s secp256k2.ModNScalar
r secp256k1.ModNScalar
s secp256k1.ModNScalar
}
// NewSignature instantiates a new signature given some r and s values.
func NewSignature(r, s *secp256k2.ModNScalar) *Signature {
func NewSignature(r, s *secp256k1.ModNScalar) *Signature {
return &Signature{*r, *s}
}
@@ -86,7 +86,7 @@ func (sig *Signature) Serialize() []byte {
// order of the group because both S and its negation are valid signatures
// modulo the order, so this forces a consistent choice to reduce signature
// malleability.
sigS := new(secp256k2.ModNScalar).Set(&sig.s)
sigS := new(secp256k1.ModNScalar).Set(&sig.s)
if sigS.IsOverHalfOrder() {
sigS.Negate()
}
@@ -135,27 +135,27 @@ func zeroArray32(b *[32]byte) {
// Note that a bool is not used here because it is not possible in Go to convert
// from a bool to numeric value in constant time and many constant-time
// operations require a numeric value.
func fieldToModNScalar(v *secp256k2.FieldVal) (secp256k2.ModNScalar, uint32) {
func fieldToModNScalar(v *secp256k1.FieldVal) (secp256k1.ModNScalar, uint32) {
var buf [32]byte
v.PutBytes(&buf)
var s secp256k2.ModNScalar
var s secp256k1.ModNScalar
overflow := s.SetBytes(&buf)
zeroArray32(&buf)
return s, overflow
}
// modNScalarToField converts a scalar modulo the group order to a field value.
func modNScalarToField(v *secp256k2.ModNScalar) secp256k2.FieldVal {
func modNScalarToField(v *secp256k1.ModNScalar) secp256k1.FieldVal {
var buf [32]byte
v.PutBytes(&buf)
var fv secp256k2.FieldVal
var fv secp256k1.FieldVal
fv.SetBytes(&buf)
return fv
}
// Verify returns whether the signature is valid for the provided hash
// and secp256k1 public key.
func (sig *Signature) Verify(hash []byte, pubKey *secp256k2.PublicKey) bool {
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].
//
@@ -221,26 +221,26 @@ func (sig *Signature) Verify(hash []byte, pubKey *secp256k2.PublicKey) bool {
// Step 2.
//
// e = H(m)
var e secp256k2.ModNScalar
var e secp256k1.ModNScalar
e.SetByteSlice(hash)
// Step 3.
//
// w = S^-1 mod N
w := new(secp256k2.ModNScalar).InverseValNonConst(&sig.s)
w := new(secp256k1.ModNScalar).InverseValNonConst(&sig.s)
// Step 4.
//
// u1 = e * w mod N
// u2 = R * w mod N
u1 := new(secp256k2.ModNScalar).Mul2(&e, w)
u2 := new(secp256k2.ModNScalar).Mul2(&sig.r, w)
u1 := new(secp256k1.ModNScalar).Mul2(&e, w)
u2 := new(secp256k1.ModNScalar).Mul2(&sig.r, w)
// Step 5.
//
// X = u1G + u2Q
var X, Q, u1G, u2Q secp256k2.JacobianPoint
var X, Q, u1G, u2Q secp256k1.JacobianPoint
pubKey.AsJacobian(&Q)
secp256k2.ScalarBaseMultNonConst(u1, &u1G)
secp256k2.ScalarMultNonConst(u2, &Q, &u2Q)
secp256k2.AddNonConst(&u1G, &u2Q, &X)
secp256k1.ScalarBaseMultNonConst(u1, &u1G)
secp256k1.ScalarMultNonConst(u2, &Q, &u2Q)
secp256k1.AddNonConst(&u1G, &u2Q, &X)
// Step 6.
//
// Fail if X is the point at infinity
@@ -250,12 +250,12 @@ func (sig *Signature) Verify(hash []byte, pubKey *secp256k2.PublicKey) bool {
// Step 7.
//
// z = (X.z)^2 mod P (X.z is the z coordinate of X)
z := new(secp256k2.FieldVal).SquareVal(&X.Z)
z := new(secp256k1.FieldVal).SquareVal(&X.Z)
// Step 8.
//
// Verified if R * z == X.x (mod P)
sigRModP := modNScalarToField(&sig.r)
result := new(secp256k2.FieldVal).Mul2(&sigRModP, z).Normalize()
result := new(secp256k1.FieldVal).Mul2(&sigRModP, z).Normalize()
if result.Equals(&X.X) {
return true
}
@@ -470,7 +470,7 @@ func ParseDERSignature(sig []byte) (*Signature, error) {
// R must be in the range [1, N-1]. Notice the check for the maximum number
// of bytes is required because SetByteSlice truncates as noted in its
// comment so it could otherwise fail to detect the overflow.
var r secp256k2.ModNScalar
var r secp256k1.ModNScalar
if len(rBytes) > 32 {
str := "invalid signature: R is larger than 256 bits"
return nil, signatureError(ErrSigRTooBig, str)
@@ -491,7 +491,7 @@ func ParseDERSignature(sig []byte) (*Signature, error) {
// S must be in the range [1, N-1]. Notice the check for the maximum number
// of bytes is required because SetByteSlice truncates as noted in its
// comment so it could otherwise fail to detect the overflow.
var s secp256k2.ModNScalar
var s secp256k1.ModNScalar
if len(sBytes) > 32 {
str := "invalid signature: S is larger than 256 bits"
return nil, signatureError(ErrSigSTooBig, str)
@@ -519,7 +519,7 @@ func ParseDERSignature(sig []byte) (*Signature, error) {
// 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 *secp256k2.ModNScalar, hash []byte) (
func sign(secKey, nonce *secp256k1.ModNScalar, hash []byte) (
*Signature, byte,
bool,
) {
@@ -562,8 +562,8 @@ func sign(secKey, nonce *secp256k2.ModNScalar, hash []byte) (
//
// Note that the point must be in affine coordinates.
k := nonce
var kG secp256k2.JacobianPoint
secp256k2.ScalarBaseMultNonConst(k, &kG)
var kG secp256k1.JacobianPoint
secp256k1.ScalarBaseMultNonConst(k, &kG)
kG.ToAffine()
// Step 3.
//
@@ -601,15 +601,15 @@ func sign(secKey, nonce *secp256k2.ModNScalar, hash []byte) (
//
// Note that this actually sets e = H(m) mod N which is correct since
// it is only used in step 5 which itself is mod N.
var e secp256k2.ModNScalar
var e secp256k1.ModNScalar
e.SetByteSlice(hash)
// Step 5 with modification B.
//
// s = k^-1(e + dr) mod N
// Repeat from step 1 if s = 0
// s = -s if s > N/2
kinv := new(secp256k2.ModNScalar).InverseValNonConst(k)
s := new(secp256k2.ModNScalar).Mul2(secKey, &r).Add(&e).Mul(kinv)
kinv := new(secp256k1.ModNScalar).InverseValNonConst(k)
s := new(secp256k1.ModNScalar).Mul2(secKey, &r).Add(&e).Mul(kinv)
if s.IsZero() {
return nil, 0, false
}
@@ -630,7 +630,7 @@ func sign(secKey, nonce *secp256k2.ModNScalar, hash []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 *secp256k2.SecretKey, hash []byte) (
func signRFC6979(secKey *secp256k1.SecretKey, hash []byte) (
*Signature,
byte,
) {
@@ -673,7 +673,7 @@ func signRFC6979(secKey *secp256k2.SecretKey, hash []byte) (
//
// Generate a deterministic nonce in [1, N-1] parameterized by the
// secret key, message being signed, and iteration count.
k := secp256k2.NonceRFC6979(secKeyBytes[:], hash, nil, nil, iteration)
k := secp256k1.NonceRFC6979(secKeyBytes[:], hash, nil, nil, iteration)
// Steps 2-6.
sig, pubKeyRecoveryCode, success := sign(secKeyScalar, k, hash)
k.Zero()
@@ -689,7 +689,7 @@ func signRFC6979(secKey *secp256k2.SecretKey, hash []byte) (
// 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 *secp256k2.SecretKey, hash []byte) *Signature {
func Sign(key *secp256k1.SecretKey, hash []byte) *Signature {
signature, _ := signRFC6979(key, hash)
return signature
}
@@ -730,7 +730,7 @@ 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 *secp256k2.SecretKey, hash []byte,
key *secp256k1.SecretKey, hash []byte,
isCompressedKey bool,
) []byte {
// Create the signature and associated pubkey recovery code and calculate
@@ -753,7 +753,7 @@ func SignCompact(
// 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 []byte) (
*secp256k2.PublicKey, bool, error,
*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
@@ -850,7 +850,7 @@ func RecoverCompact(signature, hash []byte) (
// Parse and validate the R and S signature components.
//
// Fail if r and s are not in [1, N-1].
var r, s secp256k2.ModNScalar
var r, s secp256k1.ModNScalar
if overflow := r.SetByteSlice(signature[1:33]); overflow {
str := "invalid signature: R >= group order"
return nil, false, signatureError(ErrSigRTooBig, str)
@@ -902,40 +902,40 @@ func RecoverCompact(signature, hash []byte) (
// coord originally came from a random point on the curve which means there
// must be a Y coord that satisfies the equation for a valid signature.
oddY := pubKeyRecoveryCode&pubKeyRecoveryCodeOddnessBit != 0
var y secp256k2.FieldVal
if valid := secp256k2.DecompressY(&fieldR, oddY, &y); !valid {
var y secp256k1.FieldVal
if valid := secp256k1.DecompressY(&fieldR, oddY, &y); !valid {
str := "invalid signature: not for a valid curve point"
return nil, false, signatureError(ErrPointNotOnCurve, str)
}
// Step 5.
//
// X = (r, y)
var X secp256k2.JacobianPoint
var X secp256k1.JacobianPoint
X.X.Set(fieldR.Normalize())
X.Y.Set(y.Normalize())
X.Z.SetInt(1)
// Step 6.
//
// e = H(m) mod N
var e secp256k2.ModNScalar
var e secp256k1.ModNScalar
e.SetByteSlice(hash)
// Step 7.
//
// w = r^-1 mod N
w := new(secp256k2.ModNScalar).InverseValNonConst(&r)
w := new(secp256k1.ModNScalar).InverseValNonConst(&r)
// Step 8.
//
// u1 = -(e * w) mod N
// u2 = s * w mod N
u1 := new(secp256k2.ModNScalar).Mul2(&e, w).Negate()
u2 := new(secp256k2.ModNScalar).Mul2(&s, w)
u1 := new(secp256k1.ModNScalar).Mul2(&e, w).Negate()
u2 := new(secp256k1.ModNScalar).Mul2(&s, w)
// Step 9.
//
// Q = u1G + u2X
var Q, u1G, u2X secp256k2.JacobianPoint
secp256k2.ScalarBaseMultNonConst(u1, &u1G)
secp256k2.ScalarMultNonConst(u2, &X, &u2X)
secp256k2.AddNonConst(&u1G, &u2X, &Q)
var Q, u1G, u2X secp256k1.JacobianPoint
secp256k1.ScalarBaseMultNonConst(u1, &u1G)
secp256k1.ScalarMultNonConst(u2, &X, &u2X)
secp256k1.AddNonConst(&u1G, &u2X, &Q)
// Step 10.
//
// Fail if Q is the point at infinity.
@@ -948,6 +948,6 @@ func RecoverCompact(signature, hash []byte) (
}
// Notice that the public key is in affine coordinates.
Q.ToAffine()
pubKey := secp256k2.NewPublicKey(&Q.X, &Q.Y)
pubKey := secp256k1.NewPublicKey(&Q.X, &Q.Y)
return pubKey, wasCompressed, nil
}

View File

@@ -12,12 +12,11 @@ import (
"bytes"
"errors"
"math/rand"
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/utils/chk"
"orly.dev/pkg/crypto/ec/secp256k1"
"orly.dev/pkg/encoders/hex"
"orly.dev/pkg/utils/chk"
"testing"
"time"
"orly.dev/encoders/hex"
)
// hexToBytes converts the passed hex string into bytes and will panic if there
@@ -321,8 +320,8 @@ func TestSignatureSerialize(t *testing.T) {
}, {
"zero signature",
&Signature{
r: *new(secp256k2.ModNScalar).SetInt(0),
s: *new(secp256k2.ModNScalar).SetInt(0),
r: *new(secp256k1.ModNScalar).SetInt(0),
s: *new(secp256k1.ModNScalar).SetInt(0),
},
hexToBytes("3006020100020100"),
},
@@ -657,9 +656,9 @@ func TestSignAndVerifyRandom(t *testing.T) {
if _, err := rng.Read(buf[:]); chk.T(err) {
t.Fatalf("failed to read random secret key: %v", err)
}
var secKeyScalar secp256k2.ModNScalar
var secKeyScalar secp256k1.ModNScalar
secKeyScalar.SetBytes(&buf)
secKey := secp256k2.NewSecretKey(&secKeyScalar)
secKey := secp256k1.NewSecretKey(&secKeyScalar)
// Generate a random hash to sign.
var hash [32]byte
if _, err := rng.Read(hash[:]); chk.T(err) {
@@ -798,7 +797,7 @@ func TestVerifyFailures(t *testing.T) {
s := hexToModNScalar(test.s)
sig := NewSignature(r, s)
// Ensure the verification is NOT successful.
pubKey := secp256k2.NewSecretKey(secKey).PubKey()
pubKey := secp256k1.NewSecretKey(secKey).PubKey()
if sig.Verify(hash, pubKey) {
t.Errorf(
"%s: unexpected success for invalid signature: %x",
@@ -1074,9 +1073,9 @@ func TestSignAndRecoverCompactRandom(t *testing.T) {
if _, err := rng.Read(buf[:]); chk.T(err) {
t.Fatalf("failed to read random secret key: %v", err)
}
var secKeyScalar secp256k2.ModNScalar
var secKeyScalar secp256k1.ModNScalar
secKeyScalar.SetBytes(&buf)
secKey := secp256k2.NewSecretKey(&secKeyScalar)
secKey := secp256k1.NewSecretKey(&secKeyScalar)
wantPubKey := secKey.PubKey()
// Generate a random hash to sign.
var hash [32]byte

View File

@@ -1,7 +1,7 @@
package ecdsa_test
import (
"orly.dev/utils/lol"
"orly.dev/pkg/utils/lol"
)
var (

View File

@@ -4,7 +4,7 @@
package btcec
import (
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// Error identifies an error related to public key cryptography using a

View File

@@ -1,7 +1,7 @@
package btcec
import (
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// FieldVal implements optimized fixed-precision arithmetic over the secp256k1

View File

@@ -7,10 +7,9 @@ package btcec
import (
"math/rand"
"orly.dev/utils/chk"
"orly.dev/pkg/encoders/hex"
"orly.dev/pkg/utils/chk"
"testing"
"orly.dev/encoders/hex"
)
// TestIsZero ensures that checking if a field IsZero works as expected.

View File

@@ -9,9 +9,8 @@
package btcec
import (
"orly.dev/pkg/encoders/hex"
"testing"
"orly.dev/encoders/hex"
)
func FuzzParsePubKey(f *testing.F) {

View File

@@ -4,7 +4,7 @@
package btcec
import (
secp256k2 "orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec/secp256k1"
)
// ModNScalar implements optimized 256-bit constant-time fixed-precision
@@ -24,7 +24,7 @@ import (
// that should typically be avoided when possible as conversion to big.Ints
// requires allocations, is not constant time, and is slower when working modulo
// the group order.
type ModNScalar = secp256k2.ModNScalar
type ModNScalar = secp256k1.ModNScalar
// NonceRFC6979 generates a nonce deterministically according to RFC 6979 using
// HMAC-SHA256 for the hashing function. It takes a 32-byte hash as an input
@@ -43,7 +43,7 @@ func NonceRFC6979(
extraIterations uint32,
) *ModNScalar {
return secp256k2.NonceRFC6979(
return secp256k1.NonceRFC6979(
privKey, hash, extra, version,
extraIterations,
)

View File

@@ -6,11 +6,10 @@ package musig2
import (
"fmt"
"orly.dev/crypto/ec"
"orly.dev/crypto/ec/schnorr"
"orly.dev/pkg/crypto/ec"
"orly.dev/pkg/crypto/ec/schnorr"
"orly.dev/pkg/encoders/hex"
"testing"
"orly.dev/encoders/hex"
)
var (
@@ -247,7 +246,7 @@ func BenchmarkAggregateNonces(b *testing.B) {
}
}
var testKey *btcec.PublicKey
var testKey *btcec.btcec
// BenchmarkAggregateKeys benchmarks how long it takes to aggregate public
// keys.

View File

@@ -4,9 +4,9 @@ package musig2
import (
"fmt"
"orly.dev/crypto/ec"
"orly.dev/crypto/ec/schnorr"
"orly.dev/utils/chk"
"orly.dev/pkg/crypto/ec"
"orly.dev/pkg/crypto/ec/schnorr"
"orly.dev/pkg/utils/chk"
)
var (
@@ -103,7 +103,7 @@ type contextOptions struct {
// h_tapTweak(internalKey) as there is no true script root.
bip86Tweak bool
// keySet is the complete set of signers for this context.
keySet []*btcec.PublicKey
keySet []*btcec.btcec
// numSigners is the total number of signers that will eventually be a
// part of the context.
numSigners int

View File

@@ -5,10 +5,10 @@ package musig2
import (
"bytes"
"fmt"
"orly.dev/crypto/ec"
"orly.dev/crypto/ec/chainhash"
"orly.dev/crypto/ec/schnorr"
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec"
"orly.dev/pkg/crypto/ec/chainhash"
"orly.dev/pkg/crypto/ec/schnorr"
"orly.dev/pkg/crypto/ec/secp256k1"
"sort"
)
@@ -237,7 +237,7 @@ func hasEvenY(pJ btcec.btcec) bool {
// by the parity factor. The xOnly bool specifies if this is to be an x-only
// tweak or not.
func tweakKey(
keyJ btcec.JacobianPoint, parityAcc btcec.ModNScalar,
keyJ btcec.btcec, parityAcc btcec.ModNScalar,
tweak [32]byte,
tweakAcc btcec.ModNScalar,
xOnly bool,

View File

@@ -5,17 +5,16 @@ package musig2
import (
"encoding/json"
"fmt"
"orly.dev/crypto/ec"
"orly.dev/crypto/ec/schnorr"
"orly.dev/crypto/ec/secp256k1"
"orly.dev/pkg/crypto/ec"
"orly.dev/pkg/crypto/ec/schnorr"
"orly.dev/pkg/crypto/ec/secp256k1"
"orly.dev/pkg/encoders/hex"
"os"
"path"
"strings"
"testing"
"github.com/stretchr/testify/require"
"orly.dev/encoders/hex"
)
const (
@@ -42,7 +41,7 @@ func TestMusig2KeySort(t *testing.T) {
require.NoError(t, json.Unmarshal(testVectorBytes, &testCase))
keys := make([]*btcec.btcec, len(testCase.PubKeys))
for i, keyStr := range testCase.PubKeys {
pubKey, err := btcec.ParsePubKey(mustParseHex(keyStr))
pubKey, err := btcec.btcec.ParsePubKey(mustParseHex(keyStr))
require.NoError(t, err)
keys[i] = pubKey
}

Some files were not shown because too many files have changed in this diff Show More