From 5c388914206285e33fbee70e799a09af001c2769 Mon Sep 17 00:00:00 2001 From: Samuel Ojetunde Date: Tue, 27 Oct 2026 01:23:00 +0100 Subject: [PATCH] feat(settle): check contract-account debtors when they sign A debtor that is a contract account checks its own signature, so its entry was accepted on trust and a bad one only surfaced when the batch was simulated for submission, holding up everyone in it. Accept now simulates a batch in enforcing mode as soon as a submission completes it, before recording anything. If the request brought a contract account's entry and the network refuses the batch, the request is refused with the network's reason. If it brought only account signatures (already checked locally), those are kept and the contract accounts' entries are cleared with the reason, shown in GET .../authorizations as error, so only they sign again. An unreachable RPC records nothing and the debtor retries. settletest models contract accounts whose __check_auth takes an Ed25519 signature as bytes. Tests cover a bad signature refused at the moment it is posted, then the right one settling, and a bad signature found when an account completes the batch. Closes #11. --- CHANGELOG.md | 7 ++ README.md | 13 ++- api/openapi.yaml | 8 +- internal/api/settlement.go | 8 +- internal/settle/settle.go | 91 ++++++++++++++++++-- internal/settle/settle_test.go | 129 ++++++++++++++++++++++++++-- internal/settle/settletest/chain.go | 29 ++++++- 7 files changed, 262 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf4ce04..a2632b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ All notable changes to this project are documented here. The format follows ### Added +- Contract-account debtors (smart wallets with their own `__check_auth`) are + checked when they sign, not at submission: once their batch is fully + signed, it is simulated in enforcing mode before anything is recorded. A + refused signature is rejected with the network's reason (422) if the + request brought it, or cleared with the reason in `GET …/authorizations`'s + new `error` field, keeping the accounts' valid signatures. + - On-chain settlement from the service: with `[settlement]`, closed windows are simulated against the settlement contract, debtors fetch and return their Soroban authorization entries over diff --git a/README.md b/README.md index 13832fb..202c42f 100644 --- a/README.md +++ b/README.md @@ -140,8 +140,12 @@ prepare_on_close = true # or POST /v1/windows/{n}/settle a [Tessera](https://github.com/Use-Tessera) threshold account signs the entry through its coordinator's `/v1/authorize`. 3. The service accepts a signed entry only if it is the issued one plus a valid - signature, byte for byte. Once a batch is fully signed it simulates, submits - and waits for it, then calls `settle` after the last one. + signature, byte for byte. A debtor that is a contract account (a smart + wallet with its own `__check_auth`) is checked by the network itself: when + its batch becomes fully signed, the service simulates it in enforcing mode + before recording anything, so a bad signature is refused at + `POST …/authorizations`, not at submission. Once a batch is fully signed it + is submitted and waited for, then `settle` is called after the last one. `GET /v1/windows/{n}/settlement` shows progress; failures are recorded there and retried on the next signature or re-prepare. @@ -165,11 +169,6 @@ the net position is the closing balance. `[decimals]` turns smallest units into whole units; assets without an ISO 4217 code are reported under `XXX` and named in the statement. -## Roadmap - -1. Collecting authorizations from contract-account debtors with custom - `__check_auth`, which today are checked only at simulation. - ## License [Apache-2.0](LICENSE) diff --git a/api/openapi.yaml b/api/openapi.yaml index 51039b2..1f48ddf 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -303,6 +303,7 @@ paths: hash: { type: string, description: "SHA-256 of the entry's HashIdPreimage on this network, hex: what an Ed25519 key signs." } expiration_ledger: { type: integer } signed: { type: boolean } + error: { type: string, description: "Set when a contract account's earlier signature was cleared: why the network refused it. Sign again." } "401": { $ref: "#/components/responses/Error" } "404": { $ref: "#/components/responses/Error" } "409": { $ref: "#/components/responses/Error" } @@ -313,7 +314,12 @@ paths: entry or, for a G… account, the hex Ed25519 signature of its `hash`. A signed entry must equal the issued one except for its signature, and account signatures are verified before anything is recorded; one bad - item rejects the request. Once every entry of a batch is signed, the + item rejects the request. A contract account (C…) checks its own + signature, so when a request completes a batch that has one, the batch + is simulated in enforcing mode first: a contract account's signature + the network refuses is rejected here (422) if this request brought it, + and otherwise cleared with the reason in `GET`'s `error`, keeping the + accounts' valid signatures. Once every entry of a batch is signed, the service submits it, then calls `settle` after the last batch. security: - participant: [] diff --git a/internal/api/settlement.go b/internal/api/settlement.go index 34f9e01..9fb8315 100644 --- a/internal/api/settlement.go +++ b/internal/api/settlement.go @@ -30,6 +30,8 @@ type authorization struct { Hash string `json:"hash"` ExpirationLedger uint32 `json:"expiration_ledger"` Signed bool `json:"signed"` + // Error is why a contract account's earlier signature was cleared. + Error string `json:"error,omitempty"` } func (s *Server) settlementRoutes(mux *http.ServeMux) { @@ -91,7 +93,7 @@ func (s *Server) authorizations(w http.ResponseWriter, r *http.Request) { } for _, e := range b.Entries { if e.Address == address { - out = append(out, authorization{Batch: i, Slot: e.Slot, Entry: e.Entry, Hash: e.Hash, ExpirationLedger: e.ExpirationLedger, Signed: e.Signed != ""}) + out = append(out, authorization{Batch: i, Slot: e.Slot, Entry: e.Entry, Hash: e.Hash, ExpirationLedger: e.ExpirationLedger, Signed: e.Signed != "", Error: e.Error}) } } } @@ -119,7 +121,7 @@ func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { reply(w, http.StatusBadRequest, errBody(`body must be {"authorizations": [{"batch", "slot", "entry" or "signature"}]}`)) return } - sess, err := s.Settlement.Settler.Accept(n, address, req.Authorizations) + sess, err := s.Settlement.Settler.Accept(r.Context(), n, address, req.Authorizations) switch { case errors.Is(err, settle.ErrNotPrepared): reply(w, http.StatusNotFound, errBody(err.Error())) @@ -132,7 +134,7 @@ func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { reply(w, http.StatusInternalServerError, errBody("could not record authorizations")) return } - go s.advance(n) + go s.advance(n) //nolint:gosec // G118: submission must outlive this request; it runs on the server's context reply(w, http.StatusAccepted, map[string]any{"window": n, "accepted": len(req.Authorizations), "pending": sess.Pending()}) } diff --git a/internal/settle/settle.go b/internal/settle/settle.go index 827fb46..be0a387 100644 --- a/internal/settle/settle.go +++ b/internal/settle/settle.go @@ -51,6 +51,9 @@ var ( ErrNotPrepared = errors.New("settlement has not been prepared for this window") // ErrInvalid wraps every reason a signed authorization is refused. ErrInvalid = errors.New("invalid authorization") + // errSimulation marks the network refusing a simulated call, as opposed + // to the RPC server being unreachable. + errSimulation = errors.New("simulation failed") ) // Settler prepares and drives settlement sessions. @@ -94,6 +97,9 @@ type Entry struct { Hash string `json:"hash"` ExpirationLedger uint32 `json:"expiration_ledger"` Signed string `json:"signed,omitempty"` + // Error says why a contract account's signature was cleared: the network + // refused it when its batch was simulated with every signature in place. + Error string `json:"error,omitempty"` } // Tx is a transaction's fate. @@ -217,7 +223,16 @@ func (s *Settler) Session(n uint64) (*Session, error) { // Accept records signed authorizations from the debtor at address. Either // all are accepted or none are. -func (s *Settler) Accept(n uint64, address string, sigs []Signature) (*Session, error) { +// +// An account's signature is checked here. A contract account checks its own +// (its __check_auth), so the only way to check one is to simulate its batch +// in enforcing mode, which needs every entry of the batch signed. When a +// submission completes a batch that has contract-account debtors, Accept +// simulates it first: if the submission brought a contract account's entry +// and the network refuses the batch, the submission is refused; if it brought +// only account signatures (already checked), they are kept and the contract +// accounts' entries are cleared with the reason, so only they sign again. +func (s *Settler) Accept(ctx context.Context, n uint64, address string, sigs []Signature) (*Session, error) { s.mu.Lock() defer s.mu.Unlock() sess, err := s.load(n) @@ -225,6 +240,7 @@ func (s *Settler) Accept(n uint64, address string, sigs []Signature) (*Session, return nil, err } signed := map[*Entry]string{} + batches := map[int]bool{} for i, sig := range sigs { e, entry, err := s.check(sess, address, sig) if err != nil { @@ -233,13 +249,78 @@ func (s *Settler) Accept(n uint64, address string, sigs []Signature) (*Session, if signed[e], err = xdr.MarshalBase64(entry); err != nil { return nil, err } + batches[sig.Batch] = true + } + cleared := map[*Entry]string{} + for i := range batches { + auth, contracts := assemble(sess.Batches[i], signed) + if auth == nil || len(contracts) == 0 { + continue // incomplete, or nothing a local check missed + } + err := s.enforce(ctx, sess.Batches[i], auth) + switch { + case err == nil: + continue + case !errors.Is(err, errSimulation): + return nil, err // RPC unreachable: record nothing, the debtor retries + } + for _, e := range contracts { + if _, mine := signed[e]; mine { + return nil, fmt.Errorf("%w: batch %d: the network refused the batch with your authorization: %w", ErrInvalid, i, err) + } + } + for _, e := range contracts { + cleared[e] = fmt.Sprintf("refused when batch %d was simulated with every signature in place (%v); sign again", i, err) + } } for e, v := range signed { - e.Signed = v + e.Signed, e.Error = v, "" + } + for e, why := range cleared { + e.Signed, e.Error = "", why } return sess, s.save(sess) } +// assemble returns batch b's authorizations with every signature in place, +// counting the ones in signed, and its contract-account entries; auth is nil +// while any debtor has yet to sign. +func assemble(b *Batch, signed map[*Entry]string) (auth []string, contracts []*Entry) { + if b.Tx != nil && b.Tx.Status == "SUCCESS" { + return nil, nil + } + auth = append([]string(nil), b.Auth...) + for _, e := range b.Entries { + v, ok := signed[e] + if !ok { + v = e.Signed + } + if v == "" { + return nil, nil + } + auth[e.Slot] = v + if !strkey.IsValidEd25519PublicKey(e.Address) { + contracts = append(contracts, e) + } + } + return auth, contracts +} + +// enforce simulates batch b's submit with auth attached, which the network +// checks in enforcing mode, contract accounts' __check_auth included. +func (s *Settler) enforce(ctx context.Context, b *Batch, auth []string) error { + entries, err := decodeAuth(auth) + if err != nil { + return err + } + arg, err := obligationsVal(b.Obligations) + if err != nil { + return err + } + _, _, err = s.simulate(ctx, "submit", []xdr.ScVal{arg}, entries) + return err +} + // check validates one signature against the session, returning the slot it // fills and the signed entry. func (s *Settler) check(sess *Session, address string, sig Signature) (*Entry, xdr.SorobanAuthorizationEntry, error) { @@ -305,8 +386,8 @@ func (s *Settler) check(sess *Session, address string, sig Signature) (*Entry, x return nil, none, err } } - // Contract accounts check their own signatures; simulation before - // submission enforces them. + // Contract accounts check their own signatures: Accept simulates the + // batch once every entry is signed. return want, entry, nil } @@ -416,7 +497,7 @@ func (s *Settler) simulate(ctx context.Context, fn string, args []xdr.ScVal, aut return nil, nil, err } if sim.Error != "" { - return nil, nil, fmt.Errorf("simulation failed: %s", sim.Error) + return nil, nil, fmt.Errorf("%w: %s", errSimulation, sim.Error) } return sim, tx, nil } diff --git a/internal/settle/settle_test.go b/internal/settle/settle_test.go index 7cd6aa0..ae72fb6 100644 --- a/internal/settle/settle_test.go +++ b/internal/settle/settle_test.go @@ -10,6 +10,7 @@ import ( "github.com/stellar/go-stellar-sdk/keypair" "github.com/stellar/go-stellar-sdk/network" + "github.com/stellar/go-stellar-sdk/strkey" "github.com/stellar/go-stellar-sdk/xdr" "github.com/SetOff-Org/setoff-clearing/internal/clearing" @@ -86,7 +87,7 @@ func TestSettlesAClosedWindow(t *testing.T) { } // Nothing is sent until every debtor has signed. - if _, err := s.Accept(7, parties[0].kp.Address(), sign(t, sess, parties[0])); err != nil { + if _, err := s.Accept(context.Background(), 7, parties[0].kp.Address(), sign(t, sess, parties[0])); err != nil { t.Fatal(err) } if sess, err = s.Advance(ctx, 7); err != nil || len(c.Sent()) != 0 || sess.Pending() != 1 { @@ -100,7 +101,7 @@ func TestSettlesAClosedWindow(t *testing.T) { hash, _ := hex.DecodeString(e.Hash) sig, _ := parties[1].kp.Sign(hash) signed, _ := xdr.MarshalBase64(settle.WithSignature(entry, parties[1].kp.Address(), sig)) - if _, err := s.Accept(7, parties[1].kp.Address(), []settle.Signature{{Batch: 0, Slot: e.Slot, Entry: signed}}); err != nil { + if _, err := s.Accept(context.Background(), 7, parties[1].kp.Address(), []settle.Signature{{Batch: 0, Slot: e.Slot, Entry: signed}}); err != nil { t.Fatal(err) } @@ -152,18 +153,18 @@ func TestRefusesBadAuthorizations(t *testing.T) { if name == "wrong key" { tc.sig.Slot = e.Slot // b's signature, offered for a's slot } - if _, err := s.Accept(7, tc.who, []settle.Signature{tc.sig}); !errors.Is(err, settle.ErrInvalid) { + if _, err := s.Accept(context.Background(), 7, tc.who, []settle.Signature{tc.sig}); !errors.Is(err, settle.ErrInvalid) { t.Errorf("%s: want settle.ErrInvalid, got %v", name, err) } } // One bad signature in a set rejects the whole set. - if _, err := s.Accept(7, a.kp.Address(), []settle.Signature{mine, {Batch: 0, Slot: e.Slot, Signature: "abcd"}}); !errors.Is(err, settle.ErrInvalid) { + if _, err := s.Accept(context.Background(), 7, a.kp.Address(), []settle.Signature{mine, {Batch: 0, Slot: e.Slot, Signature: "abcd"}}); !errors.Is(err, settle.ErrInvalid) { t.Fatal(err) } if got, _ := s.Session(7); got.Pending() != 2 { t.Fatalf("a rejected set was partly recorded: %d pending", got.Pending()) } - if _, err := s.Accept(8, a.kp.Address(), []settle.Signature{mine}); !errors.Is(err, settle.ErrNotPrepared) { + if _, err := s.Accept(context.Background(), 8, a.kp.Address(), []settle.Signature{mine}); !errors.Is(err, settle.ErrNotPrepared) { t.Fatal(err) } } @@ -173,7 +174,7 @@ func TestRecordsARejectedSubmitAndRetries(t *testing.T) { ctx := context.Background() sess, _ := s.Prepare(ctx, w, m) for _, p := range parties[:2] { - if _, err := s.Accept(7, p.kp.Address(), sign(t, sess, p)); err != nil { + if _, err := s.Accept(context.Background(), 7, p.kp.Address(), sign(t, sess, p)); err != nil { t.Fatal(err) } } @@ -196,3 +197,119 @@ func TestRecordsARejectedSubmitAndRetries(t *testing.T) { t.Fatalf("re-prepare dropped the settled batch: %v", err) } } + +// contractDebtor makes debtor a a contract account (a smart wallet, C…) +// that checks signatures with key, and returns its address. +func contractDebtor(t *testing.T, c *settletest.Chain, m soroban.Mapping, key *keypair.Full) string { + t.Helper() + raw := make([]byte, 32) + copy(raw, key.Address()) // any 32 bytes make a contract id + address, err := strkey.Encode(strkey.VersionByteContract, raw) + if err != nil { + t.Fatal(err) + } + m.Addresses["a"] = address + c.ContractAccount(address, key) + return address +} + +// contractSigned is the contract account's entry, signed by key the way its +// __check_auth expects: the payload hash's signature as bytes. +func contractSigned(t *testing.T, e *settle.Entry, key *keypair.Full) string { + t.Helper() + var entry xdr.SorobanAuthorizationEntry + if err := xdr.SafeUnmarshalBase64(e.Entry, &entry); err != nil { + t.Fatal(err) + } + hash, _ := hex.DecodeString(e.Hash) + sig, err := key.Sign(hash) + if err != nil { + t.Fatal(err) + } + b := xdr.ScBytes(sig) + creds := *entry.Credentials.Address + creds.Signature = xdr.ScVal{Type: xdr.ScValTypeScvBytes, Bytes: &b} + entry.Credentials.Address = &creds + out, _ := xdr.MarshalBase64(entry) + return out +} + +func entryOf(sess *settle.Session, address string) *settle.Entry { + for _, e := range sess.Batches[0].Entries { + if e.Address == address { + return e + } + } + return nil +} + +func TestRefusesABadContractAccountSignatureWhenItIsPosted(t *testing.T) { + s, c, w, m, parties := setup(t) + ctx := context.Background() + key := keypair.MustRandom() + wallet := contractDebtor(t, c, m, key) + sess, err := s.Prepare(ctx, w, m) + if err != nil { + t.Fatal(err) + } + // b, an account, signs first; its signature is checked locally. + if _, err := s.Accept(ctx, 7, parties[1].kp.Address(), sign(t, sess, parties[1])); err != nil { + t.Fatal(err) + } + // The wallet's entry completes the batch, so the batch is simulated with + // every signature in place before anything is recorded. A signature by + // the wrong key is refused now, not when the batch is submitted. + e := entryOf(sess, wallet) + bad := settle.Signature{Batch: 0, Slot: e.Slot, Entry: contractSigned(t, e, keypair.MustRandom())} + _, err = s.Accept(ctx, 7, wallet, []settle.Signature{bad}) + if !errors.Is(err, settle.ErrInvalid) || !strings.Contains(err.Error(), "__check_auth rejected") { + t.Fatalf("want the network's refusal, got %v", err) + } + if got, _ := s.Session(7); got.Pending() != 1 || len(c.Sent()) != 0 { + t.Fatalf("a refused signature was recorded or sent: %d pending, sent %v", got.Pending(), c.Sent()) + } + + // The right key is accepted, and the window settles. + good := settle.Signature{Batch: 0, Slot: e.Slot, Entry: contractSigned(t, e, key)} + if _, err := s.Accept(ctx, 7, wallet, []settle.Signature{good}); err != nil { + t.Fatal(err) + } + if sess, err = s.Advance(ctx, 7); err != nil || !sess.Settled() { + t.Fatalf("did not settle: %v", err) + } +} + +func TestABadContractSignatureFoundLaterIsClearedNotTheAccounts(t *testing.T) { + s, c, w, m, parties := setup(t) + ctx := context.Background() + wallet := contractDebtor(t, c, m, keypair.MustRandom()) + sess, err := s.Prepare(ctx, w, m) + if err != nil { + t.Fatal(err) + } + // The wallet signs first, with the wrong key. Nothing can check it yet: + // enforcing simulation needs b's signature too. + e := entryOf(sess, wallet) + bad := settle.Signature{Batch: 0, Slot: e.Slot, Entry: contractSigned(t, e, keypair.MustRandom())} + if _, err := s.Accept(ctx, 7, wallet, []settle.Signature{bad}); err != nil { + t.Fatal(err) + } + if c.Enforced() != 0 { + t.Fatal("simulated an incomplete batch") + } + // b's signature completes the batch. It is valid, so it is kept; the + // wallet's entry is cleared with the network's reason, for it to re-sign. + if _, err := s.Accept(ctx, 7, parties[1].kp.Address(), sign(t, sess, parties[1])); err != nil { + t.Fatalf("an account's valid signature was refused for someone else's: %v", err) + } + got, _ := s.Session(7) + if got.Pending() != 1 || entryOf(got, wallet).Signed != "" || !strings.Contains(entryOf(got, wallet).Error, "__check_auth rejected") { + t.Fatalf("want the wallet's entry cleared with a reason, got %+v", entryOf(got, wallet)) + } + if entryOf(got, parties[1].kp.Address()).Signed == "" { + t.Fatal("b's signature was dropped") + } + if _, err := s.Advance(ctx, 7); err != nil || len(c.Sent()) != 0 { + t.Fatalf("submitted with a signature missing: %v %v", err, c.Sent()) + } +} diff --git a/internal/settle/settletest/chain.go b/internal/settle/settletest/chain.go index 64fbd32..0e99da7 100644 --- a/internal/settle/settletest/chain.go +++ b/internal/settle/settletest/chain.go @@ -8,6 +8,7 @@ import ( "sync" "testing" + "github.com/stellar/go-stellar-sdk/keypair" "github.com/stellar/go-stellar-sdk/xdr" "github.com/SetOff-Org/setoff-clearing/internal/settle" @@ -26,6 +27,27 @@ type Chain struct { sent []string // function names, in order nonce int64 reject string // simulate this function as failing + contracts map[string]*keypair.Full + simulated int // enforcing simulations of submit +} + +// ContractAccount registers a contract account (a smart wallet, C…) whose +// __check_auth accepts a 64-byte Ed25519 signature by key of the entry's +// payload hash, given as the credentials' signature (ScVal bytes). +func (c *Chain) ContractAccount(address string, key *keypair.Full) { + c.mu.Lock() + defer c.mu.Unlock() + if c.contracts == nil { + c.contracts = map[string]*keypair.Full{} + } + c.contracts[address] = key +} + +// Enforced counts the simulations of submit run with signatures attached. +func (c *Chain) Enforced() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.simulated } // Ledger is the chain's latest ledger. @@ -108,11 +130,16 @@ func (c *Chain) simulate(env string) map[string]any { return ok } if len(op.Auth) > 0 { + c.simulated++ for _, e := range op.Auth { a := e.Credentials.Address addr, _ := a.Address.String() hash, _ := settle.PreimageHash(c.passphrase, e) - if err := settle.Verify(a.Signature, addr, hash[:]); err != nil { + if key, ok := c.contracts[addr]; ok { + if sig, isBytes := a.Signature.GetBytes(); !isBytes || key.Verify(hash[:], sig) != nil { + return map[string]any{"error": "HostError: Error(Auth, InvalidAction): " + addr + "'s __check_auth rejected the signature"} + } + } else if err := settle.Verify(a.Signature, addr, hash[:]); err != nil { return map[string]any{"error": "HostError: Error(Auth, InvalidAction): " + err.Error()} } if uint32(a.SignatureExpirationLedger) <= Ledger {