Skip to content

Commit

Permalink
remove commented code sections. fix dcrd/btcd imports
Browse files Browse the repository at this point in the history
  • Loading branch information
buck54321 committed Dec 3, 2023
1 parent 17bea05 commit 0ae4762
Show file tree
Hide file tree
Showing 13 changed files with 41 additions and 153 deletions.
7 changes: 1 addition & 6 deletions client/asset/eth/txdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,12 +407,7 @@ func (s *badgerTxDB) getTxs(n int, refID *dex.Bytes, past bool) ([]*asset.Wallet
if err != nil {
return err
}
err = item.Value(func(nonceB []byte) error {
// Does this need to be copied?
startNonceKey = nonceB
return nil
})
if err != nil {
if startNonceKey, err = item.ValueCopy(nil); err != nil {
return err
}
} else {
Expand Down
19 changes: 0 additions & 19 deletions server/comms/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,25 +261,6 @@ func (c *wsLink) logReq(id uint64, respHandler func(Link, *msgjson.Message), exp
// is equal to the response Message.ID passed to the handler (see the
// msgjson.Response case in handleMessage).
func (c *wsLink) Request(msg *msgjson.Message, f func(conn Link, msg *msgjson.Message), expireTime time.Duration, expire func()) error {
// // log.Tracef("Registering '%s' request ID %d (wsLink)", msg.Route, msg.ID)
// c.logReq(msg.ID, f, expireTime, expire)
// // Send errors are (1) connection is already down or (2) json marshal
// // failure. Any connection write errors just cause the link to quit as the
// // goroutine that actually does the write does not relay any errors back to
// // the caller. The request will eventually expire when no response comes.
// // This is not ideal - we may consider an error callback, or different
// // Send/SendNow/QueueSend functions.
// err := c.Send(msg)
// if err != nil {
// // Neither expire nor the handler should run. Stop the expire timer
// // created by logReq and delete the response handler it added. The
// // caller receives a non-nil error to deal with it.
// log.Debugf("(*wsLink).Request(route '%s') Send error, unregistering msg ID %d handler: %v",
// msg.Route, msg.ID, err)
// c.respHandler(msg.ID) // drop the removed responseHandler
// }
// return err

rawMsg, err := json.Marshal(msg)
if err != nil {
log.Errorf("Failed to marshal message: %v", err)
Expand Down
11 changes: 5 additions & 6 deletions tatanka/chain/utxo/btc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@ import (
dexbtc "decred.org/dcrdex/dex/networks/btc"
"decred.org/dcrdex/tatanka/chain"
"decred.org/dcrdex/tatanka/tanka"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson/v4"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
chainjson "github.com/decred/dcrd/rpc/jsonrpc/types/v4"
"github.com/decred/dcrd/rpcclient/v8"
"github.com/gcash/bchd/btcjson"
)

const (
Expand Down Expand Up @@ -182,7 +181,7 @@ func (c *bitcoinChain) monitorFees(ctx context.Context) {
c.log.Errorf("estimatesmartfee error: %w", err)
continue
}
atomsPerKB, err := dcrutil.NewAmount(estimateFeeResult.FeeRate)
atomsPerKB, err := btcutil.NewAmount(estimateFeeResult.FeeRate)
if err != nil {
c.log.Errorf("NewAmount error: %w", err)
continue
Expand Down Expand Up @@ -330,7 +329,7 @@ func (c *bitcoinChain) AuditHTLC(*tanka.HTLCAudit) (bool, error) {
// containing "method not found".
func isMethodNotFoundErr(err error) bool {
var errRPCMethodNotFound = int(btcjson.ErrRPCMethodNotFound.Code)
var rpcErr *dcrjson.RPCError
var rpcErr *btcjson.RPCError
return errors.As(err, &rpcErr) &&
(int(rpcErr.Code) == errRPCMethodNotFound ||
strings.Contains(strings.ToLower(rpcErr.Message), "method not found"))
Expand Down
43 changes: 11 additions & 32 deletions tatanka/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,6 @@ type Config struct {
}

type TankaClient struct {
ctx context.Context
wg *sync.WaitGroup
peerID tanka.PeerID
priv *secp256k1.PrivateKey
Expand Down Expand Up @@ -278,17 +277,8 @@ func (c *TankaClient) handleTankagram(tt *tatanka, tankagram *msgjson.Message) *
pub: pub,
decryptionKey: priv,
}
}

// The only unencrypted tankagram we'll look for is the encryption key.
if !peerExisted {
msg := gram.Message
if msg.Route != mj.RouteEncryptionKey {
// if err := c.handlePeerMessage(p, msg); err != nil {
// return msgjson.NewError(mj.ErrBadRequest, "bad raw message")
// }
return msgjson.NewError(mj.ErrBadRequest, "where's your key?")
}
if err := mj.CheckSig(msg, p.pub); err != nil {
c.log.Errorf("%s sent a unencrypted message with a bad signature: %w", p.id, err)
return msgjson.NewError(mj.ErrBadRequest, "bad gram sig")
Expand All @@ -300,7 +290,6 @@ func (c *TankaClient) handleTankagram(tt *tatanka, tankagram *msgjson.Message) *
return msgjson.NewError(mj.ErrBadRequest, "unmarshal key error")
}

var err error
p.encryptionKey, err = decodePubkeyRSA(b)
if err != nil {
c.log.Errorf("error decoding RSA pub key from %s: %v", p.id, err)
Expand Down Expand Up @@ -363,7 +352,7 @@ func (c *TankaClient) handleBroadcast(tt *tatanka, msg *msgjson.Message) {
var bcast mj.Broadcast
if err := msg.Unmarshal(&bcast); err != nil {
c.log.Errorf("%s broadcast unmarshal error: %w", err)
return // msgjson.NewError(mj.ErrBadRequest, "bad payload")
return
}
switch bcast.Topic {
case mj.TopicMarket:
Expand Down Expand Up @@ -461,7 +450,6 @@ func (c *TankaClient) Broadcast(topic tanka.Topic, subject tanka.Subject, msgTyp
}

func (c *TankaClient) Connect(ctx context.Context) (*sync.WaitGroup, error) {
c.ctx = ctx
var wg sync.WaitGroup
c.wg = &wg

Expand All @@ -482,7 +470,7 @@ func (c *TankaClient) Connect(ctx context.Context) (*sync.WaitGroup, error) {
return c.wg, nil
}

func (c *TankaClient) AddTatankaNode(peerID tanka.PeerID, uri string, cert []byte) error {
func (c *TankaClient) AddTatankaNode(ctx context.Context, peerID tanka.PeerID, uri string, cert []byte) error {
pub, err := secp256k1.ParsePubKey(peerID[:])
if err != nil {
return fmt.Errorf("error parsing pubkey from peer ID: %w", err)
Expand All @@ -503,7 +491,7 @@ func (c *TankaClient) AddTatankaNode(peerID tanka.PeerID, uri string, cert []byt
}

cm := dex.NewConnectionMaster(cl)
if err := cm.ConnectOnce(c.ctx); err != nil {
if err := cm.ConnectOnce(ctx); err != nil {
return fmt.Errorf("error connecting: %w", err)
}

Expand Down Expand Up @@ -625,27 +613,22 @@ func (c *TankaClient) tankaNodes() []*tatanka {

func (c *TankaClient) PostBond(bond *tanka.Bond) error {
msg := mj.MustRequest(mj.RoutePostBond, []*tanka.Bond{bond})
var success bool
for _, tt := range c.tankaNodes() {
var res bool
if err := c.request(tt, msg, &res); err != nil {
c.log.Errorf("error sending bond to tatanka node %s", tt.peerID)
continue
} else {
success = true
}
}
if success {
return nil
}
return errors.New("failed to report bond to any tatanka nodes")
}

func (c *TankaClient) SubscribeMarket(baseID, quoteID uint32) error {
// params := &tanka.MarketParameters{
// BaseID: baseID,
// QuoteID: quoteID,
// }
// paramsB, err := json.Marshal(params)
// if err != nil {
// return fmt.Errorf("marshal error: %w", err)
// }

mktName, err := dex.MarketName(baseID, quoteID)
if err != nil {
return fmt.Errorf("error constructing market name: %w", err)
Expand All @@ -654,7 +637,6 @@ func (c *TankaClient) SubscribeMarket(baseID, quoteID uint32) error {
msg := mj.MustRequest(mj.RouteSubscribe, &mj.Subscription{
Topic: mj.TopicMarket,
Subject: tanka.Subject(mktName),
// ChannelParameters: paramsB,
})

c.marketsMtx.Lock()
Expand Down Expand Up @@ -722,10 +704,9 @@ func (c *TankaClient) ConnectPeer(peerID tanka.PeerID, hosts ...tanka.PeerID) (*
return nil, fmt.Errorf("error parsing remote pubkey: %v", err)
}
p = &peer{
id: peerID, // tanka.PeerID
pub: remotePub, // *secp256k1.PublicKey
decryptionKey: priv, // *rsa.PrivateKey // ours
// encryptionKey: , // atomic.Value // *rsa.PublicKey, from remote peer
id: peerID,
pub: remotePub,
decryptionKey: priv,
}
}

Expand Down Expand Up @@ -819,8 +800,6 @@ func (c *TankaClient) SendTankagram(peerID tanka.PeerID, msg *msgjson.Message) (

}
return nil, nil, fmt.Errorf("no path")
// var res bool // only possible non-error result is `true`
// return c.request(tt, wrappedMsg, res)
}

func (c *TankaClient) signAndEncryptTankagram(p *peer, msg *msgjson.Message) ([]byte, error) {
Expand Down
76 changes: 4 additions & 72 deletions tatanka/client_messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ type clientJobNewRemote struct {
type clientJobRemoteDisconnect clientJobNewRemote

// clientJobFindRemotes is a clientJob that produces a list of remote tatanka
// nodes to which the client it thought to be connected.
// nodes to which the client is thought to be connected.
type clientJobFindRemotes struct {
clientID tanka.PeerID
}
Expand Down Expand Up @@ -204,7 +204,7 @@ func (t *Tatanka) handlePostBond(cl tanka.Sender, msg *msgjson.Message) *msgjson
}

if len(bonds) == 0 {
t.log.Errorf("Bond-posting client sent zero bondsl")
t.log.Errorf("Bond-posting client sent zero bonds")
return msgjson.NewError(mj.ErrBadRequest, "no bonds sent")
}

Expand Down Expand Up @@ -512,7 +512,7 @@ func (t *Tatanka) relayBroadcast(bcast *mj.Broadcast, from tanka.PeerID) {
}
}

// findPath finds an remote tatankas that are hosting the specified peer.
// findPath finds remote tatankas that are hosting the specified peer.
func (t *Tatanka) findPath(peerID tanka.PeerID) []*remoteTatanka {
job := &clientJob{
task: &clientJobFindRemotes{
Expand All @@ -532,75 +532,6 @@ func (t *Tatanka) findPath(peerID tanka.PeerID) []*remoteTatanka {
}
t.tatankasMtx.RUnlock()
return nodes
// // Attempt to locate the remote client.
// req := mj.MustRequest(mj.RoutePathInquiry, &mj.PathInquiry{ID: peerID})
// mj.SignMessage(t.priv, req)
// peers := t.tatankaNodes()
// n := len(peers)
// type result struct {
// tt *remoteTatanka
// err error
// found bool
// }
// resC := make(chan *result)
// sendReq := func(tt *remoteTatanka) {
// var found bool
// if err := tt.Request(req, func(msg *msgjson.Message) {
// if err := msg.UnmarshalResult(&found); err != nil {
// resC <- &result{err: err, tt: tt}
// } else {
// resC <- &result{found: found, tt: tt}
// }
// }); err != nil {
// resC <- &result{err: err, tt: tt}
// }
// }
// for _, tt := range peers {
// sendReq(tt)
// }
// timeout := time.After(time.Second * 5)
// rcvd := make([]*result, 0, n)
// var nFound int
// out:
// for {
// select {
// case r := <-resC:
// rcvd = append(rcvd, r)
// if r.found {
// nFound++
// }
// if len(rcvd) == n {
// break out
// }
// case <-timeout:
// t.log.Error("timed out waiting for results for path inquiry")
// break out
// case <-t.ctx.Done():
// return nil
// }
// }

// nodes := make([]*remoteTatanka, 0, nFound)
// t.remoteClientMtx.Lock()
// for _, r := range rcvd {
// if r.err != nil {
// t.log.Errorf("Path inquiry error from %s: %v", r.tt.ID, r.err)
// continue
// }
// if !r.found {
// continue
// }
// nodes = append(nodes, r.tt)
// srvs := t.remoteClients[peerID]
// if srvs == nil {
// srvs = make(map[tanka.PeerID]struct{})
// t.remoteClients[peerID] = srvs
// }
// srvs[r.tt.ID] = struct{}{}
// }
// t.remoteClientMtx.Unlock()

// return nodes
}

// handleTankagram forwards a tankagram from a locally connected client, sending
Expand Down Expand Up @@ -672,6 +603,7 @@ func (t *Tatanka) handleTankagram(c *client, msg *msgjson.Message) *msgjson.Erro
if errors.Is(err, ErrNoPath) {
sendTankagramResult(&mj.TankagramResult{Result: mj.TRTNoPath})
} else {
t.log.Errorf("Error relaying tankagram: %v", err)
sendTankagramResult(&mj.TankagramResult{Result: mj.TRTErrFromTanka})
}
}
Expand Down
3 changes: 1 addition & 2 deletions tatanka/cmd/demo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ func mainErr() (err error) {
return fmt.Errorf("failed to create custom logger: %w", err)
}

// log := logMaker.NewLogger("MAIN", dex.LevelTrace)
comms.UseLogger(logMaker.NewLogger("COMMS", dex.LevelTrace))

addrs, err := findOpenAddrs(2)
Expand Down Expand Up @@ -366,7 +365,7 @@ func newClient(ctx context.Context, addr string, peerID tanka.PeerID, i int) (*c
return nil, fmt.Errorf("ConnectOnce error: %w", err)
}

if err := tc.AddTatankaNode(peerID, "ws://"+addr, nil); err != nil {
if err := tc.AddTatankaNode(ctx, peerID, "ws://"+addr, nil); err != nil {
cm.Disconnect()
return nil, fmt.Errorf("error adding server %q", addr)
}
Expand Down
2 changes: 0 additions & 2 deletions tatanka/cmd/tatanka/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,6 @@ func parseAndSetDebugLevels(debugLevel string, UTC bool) (*dex.LoggerMaker, erro
// Set main's Logger.
log = subsystemLoggers["MAIN"]

// db.UseLogger(subsystemLoggers["DB"])

return lm, nil
}

Expand Down
4 changes: 2 additions & 2 deletions tatanka/mj/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ type TatankaConfig struct {
ID tanka.PeerID `json:"id"`
Version uint32 `json:"version"`
Chains []uint32 `json:"chains"`
// BondTier is be the senders current view of the receivers tier.
// BondTier is the senders current view of the receiver's tier.
BondTier uint64 `json:"bondTier"`
}

Expand Down Expand Up @@ -205,7 +205,7 @@ func MustNotification(route string, payload any) *msgjson.Message {
func MustResponse(id uint64, payload any, rpcErr *msgjson.Error) *msgjson.Message {
msg, err := msgjson.NewResponse(id, payload, rpcErr)
if err != nil {
panic("MustNotification error: " + err.Error())
panic("MustResponse error: " + err.Error())
}
return msg
}
10 changes: 5 additions & 5 deletions tatanka/spec/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ even when those clients are connected to different mesh nodes. Client messaging
is end-to-end encrypted, so the mesh network itself cannot read the contents.
The encrypted messaging primitive is called a "tankagram". Clients connected
to the same subscription channel might send one another tankagrams to, for
instance, communicate detaila about an ongoing atomic swap.
instance, communicate details about an ongoing atomic swap.

1) Oracle services. The mesh will coordinate distribution of network transaction
fee rates that might be used as part of validation for app actions. The mesh
Expand Down Expand Up @@ -66,10 +66,10 @@ P2P model. Tatanka Mesh does not even know what a market is.

### Outstanding Questions<a name="oustanding_questions">

- Client will self-report successes and counter-party failures, but who is in charge of
auditing these reports before inclusion into reputation? For example, the mesh
does not know what an atomic swap is, so how can a mesh node validate a reported
swap failure? Two possiblities are...
- Clients will self-report successes and counter-party failures, but who is in
charge of auditing these reports before inclusion into reputation? For example,
the mesh does not know what an atomic swap is, so how can a mesh node validate a
reported swap failure? Two possiblities are...
1) The server could audit the reports, but do so in terms of blockchain
primitives that exist outside of the context of particular applications. For
example, the server could audit reports in terms of "HTLC pairs". The
Expand Down
Loading

0 comments on commit 0ae4762

Please sign in to comment.