Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)
8 changes: 7 additions & 1 deletion api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand All @@ -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: []
Expand Down
8 changes: 5 additions & 3 deletions internal/api/settlement.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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})
}
}
}
Expand Down Expand Up @@ -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()))
Expand All @@ -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()})
}

Expand Down
91 changes: 86 additions & 5 deletions internal/settle/settle.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -217,14 +223,24 @@ 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)
if err != nil {
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 {
Expand All @@ -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) {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading