diff --git a/NETWORK.md b/NETWORK.md
index b4f3dc59..dc7b18f4 100644
--- a/NETWORK.md
+++ b/NETWORK.md
@@ -1,6 +1,6 @@
# Network Layer
-The networking subsystem authenticates peers in [NetworkProcessor][processor], manages their WebSocket sessions in
+The networking subsystem authenticates peers through [NetworkProcessor][processor] and its [HandshakeProtocol][handshake-protocol], manages their WebSocket sessions in
[NodeConnectionManager][connections], and counts traffic in [Guardian][guardian]. These owners communicate through direct
queries and asynchronous network-message and lifecycle events.
@@ -27,14 +27,16 @@ Text messages are ignored after admission to the incoming queue; ping/pong and c
## Peer Authentication
-`NetworkProcessor` starts its private peer server with two endpoints:
+`NetworkProcessor` owns admission, deadlines, connection attempts, and its private peer server. `HandshakeProtocol` owns
+one-time challenge consumption, protocol checks, signature hash construction, and response signing. The server exposes two endpoints:
-- **`POST /handshakes`** accepts a `CounterChallengeResponse`. Guardian admits the remote address, the processor consumes
+- **`POST /handshakes`** accepts a `CounterChallengeResponse`. Guardian admits the remote address, the handshake protocol consumes
a one-time challenge, checks the expected public URI, genesis hash, signature and counter-challenge prefix, then signs
a `ChallengeResponse`. Successful authentication completes the waiting outbound attempt before the HTTP response is sent.
- **`WS /`** accepts a WebSocket with `Atto-Public-Uri` and `Atto-Http-Challenge` headers. Guardian admits the remote address,
- the processor validates the headers and challenge prefix, then posts a counter-challenge to the peer's `/handshakes`
- endpoint. It checks the returned URI and signature before handing the session to `NodeConnectionManager.manage()`.
+ the processor validates the headers and the protocol validates the challenge prefix. The processor then posts a counter-challenge
+ to the peer's `/handshakes`
+ endpoint. The protocol checks the returned URI and signature before the processor hands the session to `NodeConnectionManager.manage()`.
Authentication owns its attempt reservation: failure or cancellation removes that attempt conditionally by identity;
success retains the existing five-second expiry window.
@@ -195,3 +197,5 @@ transport, feature, traffic-accounting or metrics listener to finish.
[serializer]: src/main/kotlin/cash/atto/node/network/NetworkSerializer.kt
[peer-bans]: src/main/kotlin/cash/atto/node/network/guardian/PeerBans.kt
[expected-responses]: src/main/kotlin/cash/atto/node/network/guardian/ExpectedResponses.kt
+
+[handshake-protocol]: src/main/kotlin/cash/atto/node/network/HandshakeProtocol.kt
diff --git a/README.md b/README.md
index 9b0359b7..2746360d 100644
--- a/README.md
+++ b/README.md
@@ -155,16 +155,49 @@ This project exposes endpoints for:
- **Transactions**: submit, query, and stream
- `POST /transactions`
- - `POST /transactions/stream` (publish + stream confirmation)
+ - `POST /v2/transactions` (publish and wait for confirmation)
- `GET /transactions/{hash}`
- - `GET /transactions/stream` (NDJSON live stream)
+ - `GET /v2/transactions/stream` (NDJSON live stream)
- **Accounts**: query and stream account snapshots
- - `POST /accounts`
- - `GET /accounts/{publicKey}`
- - `POST /accounts/stream` (NDJSON)
+ - `POST /accounts` (legacy response format)
+ - `POST /v2/accounts` (finite batch snapshots)
+ - `GET /v2/accounts/{address}`
+ - `POST /v2/accounts/stream` (NDJSON)
- **Receivables**, **Account Entries**, **Vote weight**, and **time** utilities
-All streaming endpoints use **NDJSON** (`application/x-ndjson`) and combine:
+Single-account v2 routes accept a full account address encoded as one path segment: `atto://...` becomes
+`atto%3A%2F%2F...`. Encode it once; raw slashes or double encoding do not identify an account route.
+
+| Operation | Route |
+| --- | --- |
+| Account snapshot | `GET /v2/accounts/{address}` |
+| Batch account snapshots | `POST /v2/accounts` with an `addresses` array |
+| Account updates | `GET /v2/accounts/{address}/stream` |
+| Receivables | `GET /v2/accounts/{address}/receivables/stream?minAmount=1` |
+| Account-entry history | `GET /v2/accounts/{address}/entries/stream?fromHeight=1&toHeight=...` |
+| Transaction history | `GET /v2/accounts/{address}/transactions/stream?fromHeight=1&toHeight=...` |
+
+V2 responses return the Commons models directly, with account, representative, receiver, and subject
+addresses instead of public-key and address-algorithm fields, including inside transaction blocks.
+Hash-algorithm fields such as `sendHashAlgorithm` remain. Amounts, heights, and timestamps use decimal
+strings in v2 JSON. `POST /v2/accounts` returns a finite JSON array using the same account lookup and
+batching as the legacy endpoint. Legacy HTTP response adapters preserve the original field sets and JSON numbers.
+Legacy transaction publication endpoints also accept key-only block identities through a local request adapter;
+canonical addresses take precedence when supplied. V2 publication requires canonical addresses for the account
+and each receiver or representative. Commons JSON decoding uses canonical models directly.
+Signatures, work, hashes, and range semantics retain their meaning. Legacy stream and public-key routes
+remain callable but are hidden from Swagger; v2 routes are documented there.
+
+All v2 NDJSON streams, including GET, POST, publication, hash, and height-range streams, attempt to flush
+a blank newline every second while open, including before the first record. Heartbeats stay between
+complete records and stop when the source completes, fails, or is cancelled. They add no domain events
+and do not extend publication deadlines. Healthy streams retain their existing lifetime. Legacy streams
+receive no heartbeat bytes.
+
+Transaction collection routes use `GET /v2/transactions/stream` for live updates and
+`POST /v2/transactions` to publish and wait for confirmation. `POST /v2/transactions/stream` is not exposed.
+
+HTTP streaming endpoints use **NDJSON** (`application/x-ndjson`) and combine:
- database results (historical)
- in-memory flows of live updates (reactive push)
@@ -181,6 +214,55 @@ a bounded live-update queue and continuing on the same subscription. Only hashes
database scan are retained to suppress overlapping or delayed live notifications; new live hashes do not grow
that set. Slow database reads or clients apply backpressure, and disconnecting cancels both the scan and live subscription.
+### Public WebSocket streams
+
+Upgrade `GET /v2/stream` on the HTTP API port to use WebSocket transport. Each connection carries one
+logical stream. Send a text `subscribe` command with the existing v2 stream `method`, `path` (including
+query parameters), and `body` for POST operations:
+
+```json
+{"type":"subscribe","request":{"method":"GET","path":"/v2/transactions/stream"}}
+```
+
+The 13 read stream operations are supported, including address, hash, height-range and POST search streams.
+Encode an `atto://` address as one percent-encoded path segment. Transaction publication and finite JSON
+queries remain HTTP-only. Commons always uses HTTP for `publish(transaction)`, including in WebSocket mode. Existing HTTP/NDJSON routes remain available and are the default
+Commons client transport; callers can explicitly select WebSocket streams.
+
+The server acknowledges subscriptions with `subscribed`. Its text JSON envelopes use `type`: `data`
+carries the unchanged endpoint record and a decimal-string `sequence`; `heartbeat` reports connection
+liveness every second while waiting; `complete` ends a successful operation; and `error` reports numeric
+`status`, `message` and whether the error is `terminal`. For example:
+
+```json
+{"type":"heartbeat"}
+{"type":"data","data":{"address":"atto://..."},"sequence":"1"}
+{"type":"complete"}
+```
+
+After accepting a data record, send `{"type":"ack","sequence":"1"}`. Acknowledgements are cumulative:
+the server sends at most 32 unacknowledged data records and waits for the final acknowledgement before
+`complete`. Continue reading heartbeats and control messages while processing data. Commons handles
+this protocol automatically.
+
+To change account membership without reconnecting, use `"mutable":true` on a subscription to one of
+the four POST streams: `/v2/accounts/stream`, `/v2/accounts/receivables/stream`,
+`/v2/accounts/entries/stream`, or `/v2/accounts/transactions/stream`. Send `update` with the same method
+and path and the full next body. Existing account subscriptions continue, newly added accounts receive
+their normal snapshot and live handoff, and removed accounts are cancelled. The server replies `updated`
+after applying the change. Filters and height ranges of retained accounts cannot change. An invalid
+update returns a nonterminal error and leaves the previous membership running. An empty mutable
+membership stays open with heartbeats. Send `{"type":"seal"}` when no more updates will follow; a sealed
+stream completes after all remaining members finish. Account and receivable streams remain live until
+the client disconnects.
+
+Heartbeats carry no ledger meaning. After an upgrade, read-operation errors use an `error` envelope
+rather than an HTTP status. A disconnect before `complete` or `error` is an interrupted stream.
+HTTP transaction publication retains its 40-second confirmation deadline.
+Closing the socket cancels its stream subscription. Slow consumers apply backpressure; domain records
+are never dropped to make room for heartbeats. A second `subscribe` command is a protocol error.
+The initial subscription must arrive within ten seconds. Each command must fit in a 256 KiB WebSocket message.
+
## How consensus works (high level)
Atto’s consensus in this codebase is vote-driven:
@@ -278,6 +360,10 @@ Major modules (packages):
- `vote/` — vote persistence and weight calculations
- `bootstrap/` — gap/dependency/head discovery and unchecked transaction recovery
+Feature-owned `AccountQueries`, `AccountEntryQueries`, `TransactionQueries`, and `ReceivableQueries` share query and
+snapshot/live stream behavior between HTTP controllers and the public WebSocket dispatcher.
+`network/HandshakeProtocol` owns peer challenge verification and signing; `NetworkProcessor` owns admission and connection lifecycle.
+
## Docker images
This repo includes multiple Dockerfiles:
diff --git a/TRANSACTION-PROCESSING.md b/TRANSACTION-PROCESSING.md
index dc3d58eb..6bed5e42 100644
--- a/TRANSACTION-PROCESSING.md
+++ b/TRANSACTION-PROCESSING.md
@@ -40,7 +40,7 @@ are listed in [Events and completion](#events-and-completion).
```mermaid
flowchart TB
- REST["TransactionPublicationController
REST submission"]
+ REST["TransactionPublicationController
HTTP submission"]
P2P["NodeConnectionManager
peer transaction push"]
PRIORITY["TransactionPrioritizer
deduplicate and buffer dependencies"]
TXWORK["Transaction queue + worker"]
@@ -163,9 +163,9 @@ listener does not mean every event changes its state. Definitions live beside th
| After-commit event | Registered by | Behavior listeners |
| --- | --- | --- |
-| `AccountUpdated` | [AccountService.add][account-service], for `ELECTION` or `BOOTSTRAP` | [TransactionPrioritizer][transaction-prioritizer], [Election][election], [ElectionProcessor][election-processor], [ElectionVoter][election-voter], [VotePrioritizer][vote-prioritizer], [VoteCleaner][vote-cleaner], [VoteWeighter][vote-weighter], [AccountController][account-controller], [TransactionPublicationController][transaction-publication], [TransactionController][transaction-controller] |
-| `ReceivableSaved` | [ReceivableService.saveAll][receivable-service], after a successful insert | [ReceivableController][receivable-controller]; each stream buffers live updates before scanning the database, then suppresses notifications matching retained database hashes |
-| `AccountEntrySaved` | [AccountEntryService.saveAll][entry-service], historical nodes | [AccountEntryController][entry-controller] |
+| `AccountUpdated` | [AccountService.add][account-service], for `ELECTION` or `BOOTSTRAP` | [TransactionPrioritizer][transaction-prioritizer], [Election][election], [ElectionProcessor][election-processor], [ElectionVoter][election-voter], [VotePrioritizer][vote-prioritizer], [VoteCleaner][vote-cleaner], [VoteWeighter][vote-weighter], [AccountQueries][account-queries], [TransactionPublicationController][transaction-publication], [TransactionQueries][transaction-queries] |
+| `ReceivableSaved` | [ReceivableService.saveAll][receivable-service], after a successful insert | [ReceivableQueries][receivable-queries]; each stream buffers live updates before scanning the database, then suppresses notifications matching retained database hashes |
+| `AccountEntrySaved` | [AccountEntryService.saveAll][entry-service], historical nodes | [AccountEntryQueries][entry-queries] |
`TransactionFailure` is the shared contract for transaction/election admission rejection, validation exceptions,
queue drops, obsolete persistence discards, election loss, and election expiry. The prioritizer consumes it to release pending state and requeue
@@ -180,7 +180,7 @@ election admission rejection, election expiry, or queue drop; `ALREADY_CONFIRMED
`ElectionRejected`, a stored exact hash completes successfully; otherwise the request receives HTTP 409. Lookup
failures and validation exceptions return a generic HTTP 500 without exposing their cause. It does not listen to
`ElectionLost` or `ElectionDiscarded`. A request timeout does not
-prove the transaction failed to commit. The separate [TransactionController][transaction-controller] consumes
+prove the transaction failed to commit. The separate [TransactionQueries][transaction-queries] consumes
`AccountUpdated` independently to emit its live query feeds; publication confirmation does not wait for those streams.
Historical vote and timestamp recording have their own queues; they are not
part of the account transaction merely because they consume the consensus event.
@@ -189,20 +189,34 @@ part of the account transaction merely because they consume the consensus event.
| State | Owner and synchronization | Completion/failure behavior to preserve |
| --- | --- | --- |
-| Pending HTTP publication attempts | [PendingTransactionRegistry][pending-publications], owned by [TransactionPublicationController][transaction-publication]; concurrent hash map with per-hash registration/removal of waiter counts and replayed results | Registration precedes publication. Same-hash requests can share one attempt; joining and retiring waiters update membership and counts atomically so a retiring caller cannot detach a new waiter; each caller removes only its own registration on completion or cancellation. A suspended election-rejection lookup completes only the attempt it observed, so it cannot replace a confirmation or complete a newer publication. |
+| Pending public API publication attempts | [PendingTransactionRegistry][pending-publications], owned by [TransactionPublicationController][transaction-publication]; concurrent hash map with per-hash registration/removal of waiter counts and replayed results | HTTP submissions call the publication workflow; public WebSockets expose read subscriptions only. Registration precedes publication. Same-hash requests can share one attempt; joining and retiring waiters update membership and counts atomically so a retiring caller cannot detach a new waiter; each caller removes only its own registration on completion or cancellation. A suspended election-rejection lookup completes only the attempt it observed, so it cannot replace a confirmation or complete a newer publication. |
| Pending hashes and dependent transactions | [TransactionPrioritizer][transaction-prioritizer]; concurrent map, with atomic operations per dependency hash | The single worker registers each dispatched hash before validation. `computeIfPresent` attaches hash-deduplicated dependents; `AccountUpdated` and processing failures detach only the completed hash, then requeue dependents outside map callbacks. Election owners report stale/obsolete candidates through failure events. The inbound duplicate filter is advisory; queue admission and the pending claim enforce unique processing. |
| Transaction priority queue and queued hash membership | [TransactionQueue][transaction-queue]; existing lock per priority group | Queue admission and dequeue claims run under the same group lock, preventing a duplicate from slipping between queue removal and pending registration. The queue deduplicates hashes even when arrival metadata or work differs. Callbacks do not mutate the queue or publish events; deferred candidates leave the queue only after their dependency takes ownership. |
-| Candidates, votes, pending consensus, cached confirmed heights | [Election][election]; one coroutine mutex for keyed elections, pending markers, their per-account height index, the bounded confirmed-height cache, clear, and detached diagnostic snapshots | Consensus moves the public key/height into `pendingConsensus` while retaining its index membership. `AccountUpdated` and `ElectionDiscarded` advance the retained confirmed height and inspect only that account's indexed active/pending heights for retirement. Newer work is preserved. Exact-height competitors receive `ElectionLost`; historical candidates receive `ElectionRejected`. Expiry and clear also remove index membership. Admission rejects pending or cached completed heights. Snapshot and size queries suspend on the same mutex as transitions. The synchronous Spring info contributor, gauge callback, and CacheSupport clear boundary use localized blocking bridges. Diagnostics copy nested candidates, votes, weights, and quorum while holding the mutex; readers cannot mutate live elections. |
+| Candidates, votes, pending consensus, cached confirmed heights | [Election][election]; one coroutine mutex for keyed elections, pending markers, their per-account height index, the bounded confirmed-height cache, clear, and detached diagnostic snapshots | Consensus moves the public key/height into `pendingConsensus` while retaining its index membership. `AccountUpdated` and `ElectionDiscarded` advance the retained confirmed height and inspect only that account's indexed active/pending heights for retirement. Newer work is preserved. Exact-height competitors receive `ElectionLost`; historical candidates receive `ElectionRejected`. Expiry and clear also remove index membership. Admission rejects pending or cached completed heights. Snapshot and size queries suspend on the same mutex as transitions. The synchronous Spring info contributor, gauge callback, and CacheSupport clear boundary use localized blocking bridges. Each voter’s candidate, latest vote timestamp, and stability-change timestamp form one immutable state. Diagnostics copy that state, nested candidates, votes, weights, and quorum while holding the mutex; readers cannot mutate live elections. |
| Votes awaiting an election and priority queue | [VotePrioritizer][vote-prioritizer]; mutex plus concurrent election membership | `ElectionStarted` releases buffered votes; rejection drops buffered votes; account completion and expiry remove active membership. |
| Consensus awaiting local persistence | [ElectionProcessor][election-processor]; `bufferLock`, hash-keyed `LinkedHashMap`, one drain worker | Exact duplicates retain their insertion position. A batch stops before repeating a public key; remaining work stays queued. On persistence failure, reuse the account reconciliation read and publish `ElectionDiscarded` before removing obsolete work. Publication occurs outside the buffer lock; failure retains that work. Unresolved entries remain queued for retry. |
| Final votes awaiting persistence | [VoteService][vote-service]; `bufferLock` protects the FIFO buffer and clear generation, with one drain worker | Each batch deduplicates signatures before insertion. Failed batches return ahead of newer votes for the worker's retry; cancellation propagates. Clearing advances the generation so an in-flight failure cannot restore cleared votes. Repository I/O runs outside the lock. |
| Account and receivable caches | [AccountRepository][account-repository], [ReceivableRepository][receivable-repository]; reactive transaction resources and completion callbacks | Account cache updates after commit and evicts on rollback/unknown completion. Receivable cache replacement/removal is conditional on the pending entry's identity, preventing a late callback from restoring deleted state. These callbacks are separate from `AccountUpdated` listeners. |
-| Account stream snapshot and latest heights | [AccountController][account-controller]; registered SharedFlow subscription and one height map per collection | `onSubscription` reads the database after registration. Concurrent live emissions wait until that subscriber finishes its snapshot; the same subscription then delivers live updates. `forwardHeightBy` suppresses equal/older heights per requested address. Cancellation or a failed query detaches the subscriber. |
-| Transaction and account-entry stream snapshots | [TransactionController][transaction-controller] and [AccountEntryController][account-entry-controller]; one registered SharedFlow subscription per hash or account range | `onSubscription` reads the database after registration, then the same subscription supplies live updates. Hash streams take one result; range streams sort and deduplicate by height and complete at the requested count. Cancellation detaches the subscription and cancels a pending snapshot read. |
-| Receivable stream snapshot hashes and live buffer | [ReceivableController][receivable-controller]; one collecting coroutine owns the snapshot hash set, one child collector sends to a bounded live channel | Live subscription starts before the database scan. Database hashes remain for delayed overlapping notifications; live-only hashes are never added. The stream drains database rows before consuming live updates. Backpressure suspends live producers, and cancellation or a failed scan cancels the live collector and channel. |
+| Account stream snapshot and latest heights | [AccountQueries][account-queries]; registered SharedFlow subscription and one height map per collection | `onSubscription` reads the database after registration. Concurrent live emissions wait until that subscriber finishes its snapshot; the same subscription then delivers live updates. `forwardHeightBy` suppresses equal/older heights per requested address. Cancellation or a failed query detaches the subscriber. |
+| Transaction and account-entry stream snapshots | [TransactionQueries][transaction-queries] and [AccountEntryQueries][account-entry-queries]; one registered SharedFlow subscription per hash or account range | `onSubscription` reads the database after registration, then the same subscription supplies live updates. Hash streams take one result; range streams sort and deduplicate by height and complete at the requested count. Cancellation detaches the subscription and cancels a pending snapshot read. |
+| Receivable stream snapshot hashes and live buffer | [ReceivableQueries][receivable-queries]; one collecting coroutine owns the snapshot hash set, one child collector sends to a bounded live channel | Live subscription starts before the database scan. Database hashes remain for delayed overlapping notifications; live-only hashes are never added. The stream drains database rows before consuming live updates. Backpressure suspends live producers, and cancellation or a failed scan cancels the live collector and channel. |
+| Public WebSocket membership and output credits | [NodeStreamDispatcher](src/main/kotlin/cash/atto/node/stream/NodeStreamDispatcher.kt) prepares plans; Commons `AttoStreamWebSocketHandler` owns one membership actor, member jobs, bounded data/control channels, and one writer per connection | Static streams collect the feature query flow once. Mutable account streams retain unchanged member jobs, start only new account flows, and cancel removed members; each query owner retains its snapshot/live handoff. The writer drops only explicitly removed members' queued records, assigns data sequence numbers, and sends at most 32 unacknowledged records. Terminal completion or source failure follows queued data and its acknowledgements. Disconnect cancels the connection scope and every member. |
| Local voting/signing jobs | [ElectionVoter][election-voter]; consensus state, mutexes, coroutine jobs | Provisional updates, cancellation, and committed final-vote publication have distinct lifecycles. Trace them before changing cleanup. |
| Bootstrap persistence observations and admission target | [BootstrapLoadMonitor][bootstrap-load]; synchronized recording and polling, with a volatile capacity snapshot | Insert completion records elapsed time, successful discovery persistence records attempted rows after commit, and non-cancelled failure records a reset. Each poll consumes its accumulated observations once. Metric registration and meter values do not drive admission. |
+V2 HTTP routes belong to the corresponding account, receivable, entry, and transaction controllers
+and return Commons models directly. HTTP controllers and public WebSocket dispatch call the same feature-owned query components.
+Those components own event subscriptions, repository reads, and snapshot/live handoff. The shared
+[range policy](src/main/kotlin/cash/atto/node/account/HeightSearchValidation.kt) validates the complete height search in queries
+and before mutable WebSocket membership changes. The finite
+`POST /v2/accounts` route also uses the existing batch lookup without adding a subscription or queue.
+Legacy transaction request decoding reconstructs addresses from old key/algorithm pairs only at the
+unprefixed publication boundary before calling the unchanged publication workflow. V2 request decoding
+requires canonical addresses. Legacy HTTP handlers
+map each response record to a compatibility representation; that mapping adds no subscription, queue,
+or persistence boundary. The shared v2 NDJSON writer inserts heartbeat lines between encoded records
+and owns the timer. Cancellation still reaches the original snapshot/live stream and stops that timer.
+
The intended admission invariant is **one current election height per public key**, with competing hashes at that
height. Validate it through the account snapshot, predecessor checks, and reachable transitions. Do not confuse it with
**one public key per save batch**, which is a separate persistence constraint enforced by `AccountService.add`.
@@ -280,7 +294,7 @@ calls. Keep source links to files and named methods so routine line movement doe
[worker]: src/main/kotlin/cash/atto/node/DemandDrivenWorker.kt
[connections]: src/main/kotlin/cash/atto/node/network/NodeConnectionManager.kt
[transaction-types]: src/main/kotlin/cash/atto/node/transaction/Transaction.kt
-[transaction-controller]: src/main/kotlin/cash/atto/node/transaction/TransactionController.kt
+[transaction-queries]: src/main/kotlin/cash/atto/node/transaction/TransactionQueries.kt
[transaction-publication]: src/main/kotlin/cash/atto/node/transaction/TransactionPublicationController.kt
[transaction-prioritizer]: src/main/kotlin/cash/atto/node/transaction/prioritization/TransactionPrioritizer.kt
[transaction-queue]: src/main/kotlin/cash/atto/node/transaction/prioritization/TransactionQueue.kt
@@ -298,12 +312,12 @@ calls. Keep source links to files and named methods so routine line movement doe
[account-types]: src/main/kotlin/cash/atto/node/account/Account.kt
[account-service]: src/main/kotlin/cash/atto/node/account/AccountService.kt
[account-repository]: src/main/kotlin/cash/atto/node/account/AccountRepository.kt
-[account-controller]: src/main/kotlin/cash/atto/node/account/AccountController.kt
+[account-queries]: src/main/kotlin/cash/atto/node/account/AccountQueries.kt
[receivable-service]: src/main/kotlin/cash/atto/node/receivable/ReceivableService.kt
[receivable-repository]: src/main/kotlin/cash/atto/node/receivable/ReceivableRepository.kt
-[receivable-controller]: src/main/kotlin/cash/atto/node/receivable/ReceivableController.kt
+[receivable-queries]: src/main/kotlin/cash/atto/node/receivable/ReceivableQueries.kt
[entry-service]: src/main/kotlin/cash/atto/node/account/entry/AccountEntryService.kt
-[entry-controller]: src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt
+[entry-queries]: src/main/kotlin/cash/atto/node/account/entry/AccountEntryQueries.kt
[vote-types]: src/main/kotlin/cash/atto/node/vote/Vote.kt
[vote-converter]: src/main/kotlin/cash/atto/node/vote/convertion/VoteConverter.kt
[vote-prioritizer]: src/main/kotlin/cash/atto/node/vote/prioritization/VotePrioritizer.kt
@@ -322,6 +336,6 @@ calls. Keep source links to files and named methods so routine line movement doe
[head-broadcaster]: src/main/kotlin/cash/atto/node/bootstrap/discovery/BootstrapHeadBroadcaster.kt
[send-discoverer]: src/main/kotlin/cash/atto/node/bootstrap/discovery/SendDiscoverer.kt
-[account-entry-controller]: src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt
+[account-entry-queries]: src/main/kotlin/cash/atto/node/account/entry/AccountEntryQueries.kt
[pending-publications]: src/main/kotlin/cash/atto/node/transaction/PendingTransactionRegistry.kt
diff --git a/build.gradle.kts b/build.gradle.kts
index 15978837..d26cd3dd 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -7,7 +7,7 @@ plugins {
kotlin("plugin.allopen") version kotlinVersion
id("org.jetbrains.kotlinx.benchmark") version "0.5.0"
- id("org.springframework.boot") version "4.1.1"
+ id("org.springframework.boot") version "4.1.2"
id("org.graalvm.buildtools.native") version "1.1.14"
id("org.jlleitschuh.gradle.ktlint") version "14.2.0"
}
@@ -53,7 +53,7 @@ allOpen {
}
dependencies {
- val commonsVersion = "8.0.0"
+ val commonsVersion = "10.0.0-SNAPSHOT"
val cucumberVersion = "7.34.8"
val springdocVersion = "3.1.1"
diff --git a/src/benchmark/kotlin/cash/atto/node/election/ElectionVoterBenchmark.kt b/src/benchmark/kotlin/cash/atto/node/election/ElectionVoterBenchmark.kt
index 9ef2b957..9659f0f4 100644
--- a/src/benchmark/kotlin/cash/atto/node/election/ElectionVoterBenchmark.kt
+++ b/src/benchmark/kotlin/cash/atto/node/election/ElectionVoterBenchmark.kt
@@ -195,8 +195,7 @@ private fun createTransaction(
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = node.network,
- algorithm = node.algorithm,
- publicKey = node.publicKey,
+ address = AttoAddress(node.algorithm, node.publicKey),
height = height.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/main/kotlin/cash/atto/node/HttpSerializationConfiguration.kt b/src/main/kotlin/cash/atto/node/HttpSerializationConfiguration.kt
new file mode 100644
index 00000000..af413c98
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/HttpSerializationConfiguration.kt
@@ -0,0 +1,29 @@
+package cash.atto.node
+
+import cash.atto.commons.spring.NdjsonHeartbeatHttpMessageWriter
+import kotlinx.serialization.json.Json
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.http.codec.ServerCodecConfigurer
+import org.springframework.http.codec.json.KotlinSerializationJsonDecoder
+import org.springframework.http.codec.json.KotlinSerializationJsonEncoder
+import org.springframework.web.reactive.config.WebFluxConfigurer
+
+@Configuration(proxyBeanMethods = false)
+class HttpSerializationConfiguration : WebFluxConfigurer {
+ private val json =
+ Json {
+ ignoreUnknownKeys = true
+ explicitNulls = false
+ encodeDefaults = true
+ }
+
+ @Bean
+ fun publicApiJson(): Json = json
+
+ override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
+ configurer.defaultCodecs().kotlinSerializationJsonDecoder(KotlinSerializationJsonDecoder(json))
+ configurer.defaultCodecs().kotlinSerializationJsonEncoder(KotlinSerializationJsonEncoder(json))
+ configurer.customCodecs().register(NdjsonHeartbeatHttpMessageWriter(json))
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/LegacyScalarSerializers.kt b/src/main/kotlin/cash/atto/node/LegacyScalarSerializers.kt
new file mode 100644
index 00000000..9e07bd70
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/LegacyScalarSerializers.kt
@@ -0,0 +1,42 @@
+package cash.atto.node
+
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.builtins.serializer
+import kotlinx.serialization.encoding.Decoder
+import kotlinx.serialization.encoding.Encoder
+
+object LegacyAmountSerializer : KSerializer {
+ override val descriptor = ULong.serializer().descriptor
+
+ override fun serialize(
+ encoder: Encoder,
+ value: AttoAmount,
+ ) = ULong.serializer().serialize(encoder, value.raw)
+
+ override fun deserialize(decoder: Decoder) = AttoAmount(ULong.serializer().deserialize(decoder))
+}
+
+object LegacyHeightSerializer : KSerializer {
+ override val descriptor = ULong.serializer().descriptor
+
+ override fun serialize(
+ encoder: Encoder,
+ value: AttoHeight,
+ ) = ULong.serializer().serialize(encoder, value.value)
+
+ override fun deserialize(decoder: Decoder) = AttoHeight(ULong.serializer().deserialize(decoder))
+}
+
+object LegacyInstantSerializer : KSerializer {
+ override val descriptor = Long.serializer().descriptor
+
+ override fun serialize(
+ encoder: Encoder,
+ value: AttoInstant,
+ ) = encoder.encodeLong(value.toEpochMilliseconds())
+
+ override fun deserialize(decoder: Decoder) = AttoInstant.fromEpochMilliseconds(decoder.decodeLong())
+}
diff --git a/src/main/kotlin/cash/atto/node/account/Account.kt b/src/main/kotlin/cash/atto/node/account/Account.kt
index 6524c69e..15b56b63 100644
--- a/src/main/kotlin/cash/atto/node/account/Account.kt
+++ b/src/main/kotlin/cash/atto/node/account/Account.kt
@@ -1,6 +1,7 @@
package cash.atto.node.account
import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -44,16 +45,14 @@ data class Account(
fun toAttoAccount(): AttoAccount =
AttoAccount(
- publicKey = publicKey,
network = network,
version = version,
- algorithm = algorithm,
+ address = AttoAddress(algorithm, publicKey),
height = AttoHeight(height.toULong()),
balance = balance,
lastTransactionHash = lastTransactionHash,
lastTransactionTimestamp = lastTransactionTimestamp.toAtto(),
- representativeAlgorithm = representativeAlgorithm,
- representativePublicKey = representativePublicKey,
+ representativeAddress = AttoAddress(representativeAlgorithm, representativePublicKey),
)
}
diff --git a/src/main/kotlin/cash/atto/node/account/AccountController.kt b/src/main/kotlin/cash/atto/node/account/AccountController.kt
index 93251da5..060837ca 100644
--- a/src/main/kotlin/cash/atto/node/account/AccountController.kt
+++ b/src/main/kotlin/cash/atto/node/account/AccountController.kt
@@ -2,30 +2,16 @@ package cash.atto.node.account
import cash.atto.commons.AttoAccount
import cash.atto.commons.AttoAddress
-import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoPublicKey
import cash.atto.commons.node.AccountSearch
-import cash.atto.commons.spring.forwardHeightBy
-import io.github.oshai.kotlinlogging.KotlinLogging
import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
-import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.asFlow
-import kotlinx.coroutines.flow.emitAll
-import kotlinx.coroutines.flow.filter
-import kotlinx.coroutines.flow.flatMapConcat
-import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.onCompletion
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.flow.onSubscription
-import org.springframework.context.event.EventListener
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
@@ -36,7 +22,7 @@ import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
-@RequestMapping("/accounts")
+@RequestMapping
@Tag(
name = "Accounts",
description =
@@ -44,20 +30,10 @@ import org.springframework.web.bind.annotation.RestController
"Since transactions mutate accounts, this reflects the result of all previous operations.",
)
class AccountController(
- val repository: AccountRepository,
- val crudRepository: AccountCrudRepository,
+ private val queries: AccountQueries,
) {
- private val logger = KotlinLogging.logger {}
-
- private val accountFlow = MutableSharedFlow()
-
- @EventListener
- suspend fun process(accountUpdated: AccountUpdated) {
- accountFlow.emit(accountUpdated.updatedAccount.toAttoAccount())
- }
-
- @GetMapping("/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamAllAccounts",
summary = "Stream all latest accounts",
responses = [
ApiResponse(
@@ -70,15 +46,28 @@ class AccountController(
),
],
)
- suspend fun stream(): Flow =
- accountFlow
- .onStart { logger.trace { "Started streaming latest transactions" } }
- .onCompletion { logger.trace { "Stopped streaming latest transactions" } }
+ @GetMapping("/v2/accounts/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(): Flow = queries.stream()
+
+ @Operation(operationId = "getAccountsByAddresses", summary = "Get accounts for given addresses")
+ @PostMapping("/v2/accounts", produces = [MediaType.APPLICATION_JSON_VALUE])
+ fun get(
+ @RequestBody search: AccountSearch,
+ ): Flow = queries.get(search)
+
+ @Operation(operationId = "getAccountByAddress", summary = "Get account by address")
+ @GetMapping("/v2/accounts/{address}")
+ suspend fun get(
+ @PathVariable address: AttoAddress,
+ ): ResponseEntity = get(address.publicKey)
+
+ suspend fun get(
+ @PathVariable publicKey: AttoPublicKey,
+ ): ResponseEntity = ResponseEntity.ofNullable(queries.get(publicKey))
- @OptIn(ExperimentalCoroutinesApi::class)
- @PostMapping
@Operation(
- summary = "Get accounts for given addresses",
+ operationId = "streamAccountsByAddresses",
+ summary = "Stream all accounts for the given addresses",
responses = [
ApiResponse(
responseCode = "200",
@@ -90,98 +79,105 @@ class AccountController(
),
],
)
- fun get(
+ @PostMapping("/v2/accounts/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(
@RequestBody search: AccountSearch,
- ): Flow {
- val publicKeys = search.addresses.map { it.publicKey }
-
- return publicKeys
- .chunked(1_000)
- .asFlow()
- .flatMapConcat { batch ->
- repository
- .findAllById(batch)
- .map { it.toAttoAccount() }
- }
- }
+ ): Flow = queries.stream(search)
- @GetMapping("/{publicKey}")
@Operation(
- summary = "Get account",
+ operationId = "streamAccountByAddress",
+ summary = "Stream account by address",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [Content(schema = Schema(implementation = AttoAccount::class))],
+ ),
+ ],
)
- suspend fun get(
+ @GetMapping("/v2/accounts/{address}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(
+ @PathVariable address: AttoAddress,
+ ): Flow = stream(address.publicKey)
+
+ suspend fun stream(
@PathVariable publicKey: AttoPublicKey,
- ): ResponseEntity {
- val account = repository.findById(publicKey)?.toAttoAccount()
- return ResponseEntity.ofNullable(account)
- }
+ ): Flow = queries.stream(publicKey)
- @PostMapping("/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun getTop100(): List = queries.getTop100()
+
+ @Hidden
@Operation(
- summary = "Stream all accounts for the given addresses",
+ operationId = "streamAllLegacyAccounts",
+ summary = "Stream all latest accounts",
responses = [
ApiResponse(
responseCode = "200",
content = [
Content(
- schema = Schema(implementation = AttoAccount::class),
+ schema = Schema(implementation = LegacyAccountResponse::class),
),
],
),
],
)
- suspend fun stream(
- @RequestBody search: AccountSearch,
- ): Flow {
- val addresses = search.addresses.toSet()
+ @GetMapping("/accounts/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(): Flow = stream().map { it.toLegacyResponse() }
- val accountDatabaseFlow =
- flow {
- val publicKeys =
- search.addresses
- .asSequence()
- .map { it.publicKey }
- .toSet()
-
- publicKeys.chunked(1000).forEach { chunk ->
- repository
- .findAllById(chunk)
- .map { it.toAttoAccount() }
- .collect { emit(it) }
- }
- }
+ @Operation(
+ operationId = "getLegacyAccountsByAddresses",
+ summary = "Get accounts for given addresses",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyAccountResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @PostMapping("/accounts")
+ fun legacyGet(
+ @RequestBody search: AccountSearch,
+ ): Flow = get(search).map { it.toLegacyResponse() }
- return accountFlow
- // Register before reading the snapshot so concurrent updates wait for the handoff.
- .onSubscription { emitAll(accountDatabaseFlow) }
- .filter { addresses.contains(AttoAddress(it.algorithm, it.publicKey)) }
- .forwardHeightBy { it.address }
- .onStart { logger.trace { "Started streaming accounts for $addresses" } }
- .onCompletion { logger.trace { "Stopped streaming accounts for $addresses" } }
- }
+ @Hidden
+ @Operation(operationId = "getLegacyAccountByPublicKey")
+ @GetMapping("/accounts/{publicKey}")
+ suspend fun legacyGet(
+ @PathVariable publicKey: AttoPublicKey,
+ ): ResponseEntity = get(publicKey).let { ResponseEntity(it.body?.toLegacyResponse(), it.headers, it.statusCode) }
- @GetMapping("/{publicKey}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ @Hidden
@Operation(
- summary = "Stream account",
+ operationId = "streamLegacyAccountsByAddresses",
+ summary = "Stream all accounts for the given addresses",
responses = [
ApiResponse(
responseCode = "200",
content = [
Content(
- schema = Schema(implementation = AttoAccount::class),
+ schema = Schema(implementation = LegacyAccountResponse::class),
),
],
),
],
)
- suspend fun stream(
+ @PostMapping("/accounts/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
+ @RequestBody search: AccountSearch,
+ ): Flow = stream(search).map { it.toLegacyResponse() }
+
+ @Hidden
+ @Operation(operationId = "streamLegacyAccountByPublicKey")
+ @GetMapping("/accounts/{publicKey}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
@PathVariable publicKey: AttoPublicKey,
- ): Flow {
- val address = AttoAddress(AttoAlgorithm.V1, publicKey)
- return stream(AccountSearch(setOf(address)))
- }
+ ): Flow = stream(publicKey).map { it.toLegacyResponse() }
- @GetMapping("/top")
@Hidden
- suspend fun getTop100(): List = crudRepository.getTop100().map { it.toAttoAccount() }
+ @Operation(operationId = "getLegacyTop100Accounts")
+ @GetMapping("/accounts/top")
+ suspend fun legacyGetTop100(): List = getTop100().map { it.toLegacyResponse() }
}
diff --git a/src/main/kotlin/cash/atto/node/account/AccountQueries.kt b/src/main/kotlin/cash/atto/node/account/AccountQueries.kt
new file mode 100644
index 00000000..c2240334
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/account/AccountQueries.kt
@@ -0,0 +1,101 @@
+package cash.atto.node.account
+
+import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.node.AccountSearch
+import cash.atto.commons.spring.forwardHeightBy
+import io.github.oshai.kotlinlogging.KotlinLogging
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asFlow
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.flatMapConcat
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onCompletion
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.onSubscription
+import org.springframework.context.event.EventListener
+import org.springframework.stereotype.Component
+
+@Component
+class AccountQueries(
+ private val repository: AccountRepository,
+ private val crudRepository: AccountCrudRepository,
+) {
+ private val logger = KotlinLogging.logger {}
+
+ private val accountFlow = MutableSharedFlow()
+
+ @EventListener
+ suspend fun process(accountUpdated: AccountUpdated) {
+ accountFlow.emit(accountUpdated.updatedAccount.toAttoAccount())
+ }
+
+ suspend fun stream(): Flow =
+ accountFlow
+ .onStart { logger.trace { "Started streaming latest transactions" } }
+ .onCompletion { logger.trace { "Stopped streaming latest transactions" } }
+
+ @OptIn(ExperimentalCoroutinesApi::class)
+ fun get(search: AccountSearch): Flow {
+ val publicKeys = search.addresses.map { it.publicKey }
+
+ return publicKeys
+ .chunked(1_000)
+ .asFlow()
+ .flatMapConcat { batch ->
+ repository
+ .findAllById(batch)
+ .map { it.toAttoAccount() }
+ }
+ }
+
+ suspend fun get(address: AttoAddress): AttoAccount? = get(address.publicKey)
+
+ suspend fun get(publicKey: AttoPublicKey): AttoAccount? {
+ val account = repository.findById(publicKey)?.toAttoAccount()
+ return account
+ }
+
+ suspend fun stream(search: AccountSearch): Flow {
+ val addresses = search.addresses.toSet()
+
+ val accountDatabaseFlow =
+ flow {
+ val publicKeys =
+ search.addresses
+ .asSequence()
+ .map { it.publicKey }
+ .toSet()
+
+ publicKeys.chunked(1000).forEach { chunk ->
+ repository
+ .findAllById(chunk)
+ .map { it.toAttoAccount() }
+ .collect { emit(it) }
+ }
+ }
+
+ return accountFlow
+ // Register before reading the snapshot so concurrent updates wait for the handoff.
+ .onSubscription { emitAll(accountDatabaseFlow) }
+ .filter { addresses.contains(it.address) }
+ .forwardHeightBy { it.address }
+ .onStart { logger.trace { "Started streaming accounts for $addresses" } }
+ .onCompletion { logger.trace { "Stopped streaming accounts for $addresses" } }
+ }
+
+ suspend fun stream(address: AttoAddress): Flow = stream(address.publicKey)
+
+ suspend fun stream(publicKey: AttoPublicKey): Flow {
+ val address = AttoAddress(AttoAlgorithm.V1, publicKey)
+ return stream(AccountSearch(setOf(address)))
+ }
+
+ suspend fun getTop100(): List = crudRepository.getTop100().map { it.toAttoAccount() }
+}
diff --git a/src/main/kotlin/cash/atto/node/account/AccountService.kt b/src/main/kotlin/cash/atto/node/account/AccountService.kt
index 93d6b9fc..9c4a7b7a 100644
--- a/src/main/kotlin/cash/atto/node/account/AccountService.kt
+++ b/src/main/kotlin/cash/atto/node/account/AccountService.kt
@@ -43,16 +43,16 @@ class AccountService(
AccountTransaction(
account =
Account(
- publicKey = block.publicKey,
+ publicKey = block.address.publicKey,
network = block.network,
version = block.version,
- algorithm = block.algorithm,
+ algorithm = block.address.algorithm,
height = block.height.value.toLong() - 1,
balance = AttoAmount.MIN,
lastTransactionHash = block.hash,
lastTransactionTimestamp = block.timestamp.toJavaInstant(),
- representativeAlgorithm = block.representativeAlgorithm,
- representativePublicKey = block.representativePublicKey,
+ representativeAlgorithm = block.representativeAddress.algorithm,
+ representativePublicKey = block.representativeAddress.publicKey,
),
transaction = tx,
)
@@ -92,13 +92,13 @@ class AccountService(
lastTransactionTimestamp = block.timestamp.toJavaInstant(),
representativeAlgorithm =
if (block is RepresentativeSupport) {
- block.representativeAlgorithm
+ block.representativeAddress.algorithm
} else {
this.representativeAlgorithm
},
representativePublicKey =
if (block is RepresentativeSupport) {
- block.representativePublicKey
+ block.representativeAddress.publicKey
} else {
this.representativePublicKey
},
@@ -128,11 +128,11 @@ class AccountService(
val (subjectAlgorithm, subjectPublicKey) =
when (block) {
is AttoChangeBlock -> {
- block.representativeAlgorithm to block.representativePublicKey
+ block.representativeAddress.algorithm to block.representativeAddress.publicKey
}
is AttoSendBlock -> {
- block.receiverAlgorithm to block.receiverPublicKey
+ block.receiverAddress.algorithm to block.receiverAddress.publicKey
}
is AttoReceiveBlock, is AttoOpenBlock -> {
diff --git a/src/main/kotlin/cash/atto/node/account/HeightSearchValidation.kt b/src/main/kotlin/cash/atto/node/account/HeightSearchValidation.kt
new file mode 100644
index 00000000..7d572381
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/account/HeightSearchValidation.kt
@@ -0,0 +1,15 @@
+package cash.atto.node.account
+
+import cash.atto.commons.node.HeightSearch
+import org.springframework.http.HttpStatus
+import org.springframework.web.server.ResponseStatusException
+
+/** Validate the complete search before any member starts or changes its live subscription. */
+internal fun HeightSearch.validateRanges() {
+ if (search.any { it.fromHeight.value == 0UL }) {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "fromHeight can't be zero")
+ }
+ if (search.any { it.fromHeight > it.toHeight }) {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "toHeight must be greater or equal to fromHeight")
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/account/LegacyAccountResponse.kt b/src/main/kotlin/cash/atto/node/account/LegacyAccountResponse.kt
new file mode 100644
index 00000000..e8bec08b
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/account/LegacyAccountResponse.kt
@@ -0,0 +1,50 @@
+package cash.atto.node.account
+
+import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoVersion
+import cash.atto.node.LegacyAmountSerializer
+import cash.atto.node.LegacyHeightSerializer
+import cash.atto.node.LegacyInstantSerializer
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class LegacyAccountResponse(
+ val publicKey: AttoPublicKey,
+ val network: AttoNetwork,
+ val version: AttoVersion,
+ val algorithm: AttoAlgorithm,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ val height: AttoHeight,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val balance: AttoAmount,
+ val lastTransactionHash: AttoHash,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ val lastTransactionTimestamp: AttoInstant,
+ val representativeAlgorithm: AttoAlgorithm,
+ val representativePublicKey: AttoPublicKey,
+)
+
+fun AttoAccount.toLegacyResponse(): LegacyAccountResponse =
+ LegacyAccountResponse(
+ publicKey = address.publicKey,
+ network = network,
+ version = version,
+ algorithm = address.algorithm,
+ height = height,
+ balance = balance,
+ lastTransactionHash = lastTransactionHash,
+ lastTransactionTimestamp = lastTransactionTimestamp,
+ representativeAlgorithm = representativeAddress.algorithm,
+ representativePublicKey = representativeAddress.publicKey,
+ )
diff --git a/src/main/kotlin/cash/atto/node/account/entry/AccountEntry.kt b/src/main/kotlin/cash/atto/node/account/entry/AccountEntry.kt
index a3be41be..48c7d560 100644
--- a/src/main/kotlin/cash/atto/node/account/entry/AccountEntry.kt
+++ b/src/main/kotlin/cash/atto/node/account/entry/AccountEntry.kt
@@ -1,6 +1,7 @@
package cash.atto.node.account.entry
import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlockType
@@ -36,12 +37,10 @@ data class AccountEntry(
fun AccountEntry.toAtto(): AttoAccountEntry =
AttoAccountEntry(
hash = hash,
- algorithm = algorithm,
- publicKey = publicKey,
+ address = AttoAddress(algorithm, publicKey),
height = height,
blockType = blockType,
- subjectAlgorithm = subjectAlgorithm,
- subjectPublicKey = subjectPublicKey,
+ subjectAddress = AttoAddress(subjectAlgorithm, subjectPublicKey),
previousBalance = previousBalance,
balance = balance,
timestamp = timestamp.toAtto(),
@@ -50,12 +49,12 @@ fun AccountEntry.toAtto(): AttoAccountEntry =
fun AttoAccountEntry.toEntity(): AccountEntry =
AccountEntry(
hash = hash,
- algorithm = algorithm,
- publicKey = publicKey,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
height = height,
blockType = blockType,
- subjectAlgorithm = subjectAlgorithm,
- subjectPublicKey = subjectPublicKey,
+ subjectAlgorithm = subjectAddress.algorithm,
+ subjectPublicKey = subjectAddress.publicKey,
previousBalance = previousBalance,
balance = balance,
timestamp = timestamp.toJavaInstant(),
diff --git a/src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt b/src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt
index 4bb29ecf..0bd162e5 100644
--- a/src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt
+++ b/src/main/kotlin/cash/atto/node/account/entry/AccountEntryController.kt
@@ -2,33 +2,18 @@ package cash.atto.node.account.entry
import cash.atto.commons.AttoAccountEntry
import cash.atto.commons.AttoAddress
-import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoHeight
import cash.atto.commons.AttoPublicKey
-import cash.atto.commons.node.AccountHeightSearch
import cash.atto.commons.node.HeightSearch
-import cash.atto.commons.spring.sortByHeight
-import cash.atto.commons.toAttoHeight
-import cash.atto.commons.toBigInteger
-import io.github.oshai.kotlinlogging.KotlinLogging
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.emitAll
-import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.merge
-import kotlinx.coroutines.flow.onCompletion
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.flow.onSubscription
-import kotlinx.coroutines.flow.take
-import org.springframework.context.event.EventListener
-import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
@@ -37,7 +22,6 @@ import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
-import org.springframework.web.server.ResponseStatusException
@RestController
@RequestMapping
@@ -46,19 +30,10 @@ import org.springframework.web.server.ResponseStatusException
description = "A user-friendly view of account activity. Recommended for displaying transaction history in UIs.",
)
class AccountEntryController(
- val repository: AccountEntryRepository,
+ private val queries: AccountEntryQueries,
) {
- private val logger = KotlinLogging.logger {}
-
- private val entryFlow = MutableSharedFlow()
-
- @EventListener
- suspend fun process(event: AccountEntrySaved) {
- entryFlow.emit(event.entry.toAtto())
- }
-
- @GetMapping("/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamAllAccountEntries",
summary = "Stream all latest account entries",
responses = [
ApiResponse(
@@ -71,13 +46,11 @@ class AccountEntryController(
),
],
)
- suspend fun stream(): Flow =
- entryFlow
- .onStart { logger.trace { "Started streaming latest account entries" } }
- .onCompletion { logger.trace { "Stopped streaming latest account entries" } }
+ @GetMapping("/v2/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(): Flow = queries.stream()
- @GetMapping("/accounts/entries/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamAccountEntryByHash",
summary = "Stream a single account entry",
description =
"Allows clients to track the confirmation of a transaction in real-time by streaming a single account entry by hash. " +
@@ -93,19 +66,13 @@ class AccountEntryController(
),
],
)
+ @GetMapping("/v2/accounts/entries/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
suspend fun stream(
@PathVariable hash: AttoHash,
- ): Flow =
- entryFlow
- .onSubscription {
- repository.findById(hash)?.let { emit(it.toAtto()) }
- }.filter { it.hash == hash }
- .onStart { logger.trace { "Started streaming $hash account entry" } }
- .onCompletion { logger.trace { "Stopped streaming $hash account entry" } }
- .take(1)
+ ): Flow = queries.stream(hash)
- @PostMapping("/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamAccountEntriesByHeightRanges",
summary = "Stream account entries by height range",
responses = [
ApiResponse(
@@ -118,74 +85,101 @@ class AccountEntryController(
),
],
)
+ @PostMapping("/v2/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
suspend fun streamMultiple(
@RequestBody search: HeightSearch,
- ): Flow {
- val accountRanges = search.search
+ ): Flow = queries.streamMultiple(search)
- if (accountRanges.any { it.fromHeight == 0UL.toAttoHeight() }) {
- throw ResponseStatusException(HttpStatus.BAD_REQUEST, "fromHeight can't be zero")
- }
- if (accountRanges.any { it.fromHeight > it.toHeight }) {
- throw ResponseStatusException(HttpStatus.BAD_REQUEST, "toHeight must be greater or equal to fromHeight")
- }
+ @Operation(
+ operationId = "streamAccountEntriesByAddress",
+ summary = "Stream account entries by address and height range",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [Content(schema = Schema(implementation = AttoAccountEntry::class))],
+ ),
+ ],
+ )
+ @GetMapping("/v2/accounts/{address}/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(
+ @PathVariable address: AttoAddress,
+ @RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
+ @RequestParam(required = false) toHeight: AttoHeight?,
+ ): Flow = stream(address.publicKey, fromHeight, toHeight)
- val accountFlows =
- accountRanges.map { range ->
- val publicKey = range.address.publicKey
- val fromHeight = range.fromHeight
- val toHeight = range.toHeight
- val expectedCount =
- (range.toHeight - range.fromHeight + 1UL).let {
- if (it.value > Int.MAX_VALUE.toUInt()) Int.MAX_VALUE else it.value.toInt()
- }
+ suspend fun stream(
+ @PathVariable publicKey: AttoPublicKey,
+ @RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
+ @RequestParam(required = false) toHeight: AttoHeight?,
+ ): Flow = queries.stream(publicKey, fromHeight, toHeight)
- entryFlow
- .onSubscription {
- emitAll(
- repository
- .findAsc(publicKey, fromHeight.value.toBigInteger(), toHeight.value.toBigInteger())
- .map { it.toAtto() },
- )
- }.filter { it.publicKey == publicKey && it.height in fromHeight..toHeight }
- .sortByHeight(fromHeight)
- .take(expectedCount)
- }
+ @Hidden
+ @Operation(
+ operationId = "streamAllLegacyAccountEntries",
+ summary = "Stream all latest account entries",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyAccountEntryResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @GetMapping("/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(): Flow = stream().map { it.toLegacyResponse() }
- return merge(*accountFlows.toTypedArray())
- .onStart {
- logger.trace { "Started streaming entries for ${accountRanges.size} accounts" }
- }.onCompletion {
- logger.trace { "Stopped streaming entries for ${accountRanges.size} accounts" }
- }
- }
+ @Hidden
+ @Operation(
+ operationId = "streamLegacyAccountEntryByHash",
+ summary = "Stream a single account entry",
+ description =
+ "Allows clients to track the confirmation of a transaction in real-time by streaming a single account entry by hash. " +
+ "Useful when the transaction hash is shared ahead of time, like in payment protocols.",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyAccountEntryResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @GetMapping("/accounts/entries/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
+ @PathVariable hash: AttoHash,
+ ): Flow = stream(hash).map { it.toLegacyResponse() }
- @GetMapping("/accounts/{publicKey}/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ @Hidden
@Operation(
- summary = "Stream account entries by height",
+ operationId = "streamLegacyAccountEntriesByHeightRanges",
+ summary = "Stream account entries by height range",
responses = [
ApiResponse(
responseCode = "200",
content = [
Content(
- schema = Schema(implementation = AttoAccountEntry::class),
+ schema = Schema(implementation = LegacyAccountEntryResponse::class),
),
],
),
],
)
- suspend fun stream(
+ @PostMapping("/accounts/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStreamMultiple(
+ @RequestBody search: HeightSearch,
+ ): Flow = streamMultiple(search).map { it.toLegacyResponse() }
+
+ @Hidden
+ @Operation(operationId = "streamLegacyAccountEntriesByPublicKey")
+ @GetMapping("/accounts/{publicKey}/entries/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
@PathVariable publicKey: AttoPublicKey,
@RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
@RequestParam(required = false) toHeight: AttoHeight?,
- ): Flow {
- val transactionSearch =
- AccountHeightSearch(
- AttoAddress(AttoAlgorithm.V1, publicKey),
- fromHeight,
- (toHeight ?: AttoHeight.MAX),
- )
- val search = HeightSearch(listOf(transactionSearch))
- return streamMultiple(search)
- }
+ ): Flow = stream(publicKey, fromHeight, toHeight).map { it.toLegacyResponse() }
}
diff --git a/src/main/kotlin/cash/atto/node/account/entry/AccountEntryQueries.kt b/src/main/kotlin/cash/atto/node/account/entry/AccountEntryQueries.kt
new file mode 100644
index 00000000..b336fb7e
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/account/entry/AccountEntryQueries.kt
@@ -0,0 +1,110 @@
+package cash.atto.node.account.entry
+
+import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.node.AccountHeightSearch
+import cash.atto.commons.node.HeightSearch
+import cash.atto.commons.spring.sortByHeight
+import cash.atto.commons.toBigInteger
+import cash.atto.node.account.validateRanges
+import io.github.oshai.kotlinlogging.KotlinLogging
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.flow.onCompletion
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.onSubscription
+import kotlinx.coroutines.flow.take
+import org.springframework.context.event.EventListener
+import org.springframework.stereotype.Component
+
+@Component
+class AccountEntryQueries(
+ private val repository: AccountEntryRepository,
+) {
+ private val logger = KotlinLogging.logger {}
+
+ private val entryFlow = MutableSharedFlow()
+
+ @EventListener
+ suspend fun process(event: AccountEntrySaved) {
+ entryFlow.emit(event.entry.toAtto())
+ }
+
+ suspend fun stream(): Flow =
+ entryFlow
+ .onStart { logger.trace { "Started streaming latest account entries" } }
+ .onCompletion { logger.trace { "Stopped streaming latest account entries" } }
+
+ suspend fun stream(hash: AttoHash): Flow =
+ entryFlow
+ .onSubscription {
+ repository.findById(hash)?.let { emit(it.toAtto()) }
+ }.filter { it.hash == hash }
+ .onStart { logger.trace { "Started streaming $hash account entry" } }
+ .onCompletion { logger.trace { "Stopped streaming $hash account entry" } }
+ .take(1)
+
+ suspend fun streamMultiple(search: HeightSearch): Flow {
+ val accountRanges = search.search
+
+ search.validateRanges()
+
+ val accountFlows =
+ accountRanges.map { range ->
+ val publicKey = range.address.publicKey
+ val fromHeight = range.fromHeight
+ val toHeight = range.toHeight
+ val expectedCount =
+ (range.toHeight - range.fromHeight + 1UL).let {
+ if (it.value > Int.MAX_VALUE.toUInt()) Int.MAX_VALUE else it.value.toInt()
+ }
+
+ entryFlow
+ .onSubscription {
+ emitAll(
+ repository
+ .findAsc(publicKey, fromHeight.value.toBigInteger(), toHeight.value.toBigInteger())
+ .map { it.toAtto() },
+ )
+ }.filter { it.address.publicKey == publicKey && it.height in fromHeight..toHeight }
+ .sortByHeight(fromHeight)
+ .take(expectedCount)
+ }
+
+ return merge(*accountFlows.toTypedArray())
+ .onStart {
+ logger.trace { "Started streaming entries for ${accountRanges.size} accounts" }
+ }.onCompletion {
+ logger.trace { "Stopped streaming entries for ${accountRanges.size} accounts" }
+ }
+ }
+
+ suspend fun stream(
+ address: AttoAddress,
+ fromHeight: AttoHeight,
+ toHeight: AttoHeight?,
+ ): Flow = stream(address.publicKey, fromHeight, toHeight)
+
+ suspend fun stream(
+ publicKey: AttoPublicKey,
+ fromHeight: AttoHeight,
+ toHeight: AttoHeight?,
+ ): Flow {
+ val transactionSearch =
+ AccountHeightSearch(
+ AttoAddress(AttoAlgorithm.V1, publicKey),
+ fromHeight,
+ (toHeight ?: AttoHeight.MAX),
+ )
+ val search = HeightSearch(listOf(transactionSearch))
+ return streamMultiple(search)
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/account/entry/LegacyAccountEntryResponse.kt b/src/main/kotlin/cash/atto/node/account/entry/LegacyAccountEntryResponse.kt
new file mode 100644
index 00000000..152fd9ba
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/account/entry/LegacyAccountEntryResponse.kt
@@ -0,0 +1,55 @@
+package cash.atto.node.account.entry
+
+import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoBlockType
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoPublicKey
+import cash.atto.node.LegacyAmountSerializer
+import cash.atto.node.LegacyHeightSerializer
+import cash.atto.node.LegacyInstantSerializer
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class LegacyAccountEntryResponse(
+ val hash: AttoHash,
+ val algorithm: AttoAlgorithm,
+ val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ val height: AttoHeight,
+ val blockType: AttoBlockType,
+ val subjectAlgorithm: AttoAlgorithm,
+ val subjectPublicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val previousBalance: AttoAmount,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val balance: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ val timestamp: AttoInstant,
+) {
+ val address = AttoAddress(algorithm, publicKey)
+ val subjectAddress = AttoAddress(subjectAlgorithm, subjectPublicKey)
+}
+
+fun AttoAccountEntry.toLegacyResponse(): LegacyAccountEntryResponse =
+ LegacyAccountEntryResponse(
+ hash = hash,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ height = height,
+ blockType = blockType,
+ subjectAlgorithm = subjectAddress.algorithm,
+ subjectPublicKey = subjectAddress.publicKey,
+ previousBalance = previousBalance,
+ balance = balance,
+ timestamp = timestamp,
+ )
diff --git a/src/main/kotlin/cash/atto/node/bootstrap/discovery/GapDiscoverer.kt b/src/main/kotlin/cash/atto/node/bootstrap/discovery/GapDiscoverer.kt
index b1d1e830..4723cd8f 100644
--- a/src/main/kotlin/cash/atto/node/bootstrap/discovery/GapDiscoverer.kt
+++ b/src/main/kotlin/cash/atto/node/bootstrap/discovery/GapDiscoverer.kt
@@ -109,7 +109,7 @@ class GapDiscoverer(
@EventListener
suspend fun process(message: InboundNetworkMessage) {
- val publicKey = message.payload.transaction.block.publicKey
+ val publicKey = message.payload.transaction.block.address.publicKey
val session = activeSessions[publicKey] ?: return
if (session.offer(message)) {
activeSessions.replace(publicKey, session, session)
diff --git a/src/main/kotlin/cash/atto/node/bootstrap/discovery/LastDiscoverer.kt b/src/main/kotlin/cash/atto/node/bootstrap/discovery/LastDiscoverer.kt
index b57d8357..ca680051 100644
--- a/src/main/kotlin/cash/atto/node/bootstrap/discovery/LastDiscoverer.kt
+++ b/src/main/kotlin/cash/atto/node/bootstrap/discovery/LastDiscoverer.kt
@@ -72,7 +72,7 @@ class LastDiscoverer(
logger.trace { "Received bootstrap head transaction ${transaction.hash}" }
- val account = accountRepository.getByAlgorithmAndPublicKey(block.algorithm, block.publicKey, block.network)
+ val account = accountRepository.getByAlgorithmAndPublicKey(block.address.algorithm, block.address.publicKey, block.network)
if (account.height.toULong() == block.height.value) {
return
diff --git a/src/main/kotlin/cash/atto/node/bootstrap/discovery/SendDiscoverer.kt b/src/main/kotlin/cash/atto/node/bootstrap/discovery/SendDiscoverer.kt
index 63849e40..004ebeea 100644
--- a/src/main/kotlin/cash/atto/node/bootstrap/discovery/SendDiscoverer.kt
+++ b/src/main/kotlin/cash/atto/node/bootstrap/discovery/SendDiscoverer.kt
@@ -112,11 +112,11 @@ class SendDiscoverer(
}
val block = transaction.block
- if (uncheckedTransactionRepository.hasHigherTransaction(block.publicKey, block.height) != 0L) {
+ if (uncheckedTransactionRepository.hasHigherTransaction(block.address.publicKey, block.height) != 0L) {
skippedForGap.increment()
logger.debug {
"Skipping missing send transaction ${transaction.hash} at height ${block.height} because account " +
- "${block.publicKey} has a higher unchecked transaction"
+ "${block.address.publicKey} has a higher unchecked transaction"
}
return
}
diff --git a/src/main/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransaction.kt b/src/main/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransaction.kt
index 55ce210a..dfb5fa60 100644
--- a/src/main/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransaction.kt
+++ b/src/main/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransaction.kt
@@ -26,7 +26,7 @@ data class UncheckedTransaction(
@Id
val hash = block.hash
- val publicKey = block.publicKey
+ val publicKey = block.address.publicKey
val height = block.height
@Transient
diff --git a/src/main/kotlin/cash/atto/node/convertion/TransactionConverter.kt b/src/main/kotlin/cash/atto/node/convertion/TransactionConverter.kt
index 181553a7..82576eed 100644
--- a/src/main/kotlin/cash/atto/node/convertion/TransactionConverter.kt
+++ b/src/main/kotlin/cash/atto/node/convertion/TransactionConverter.kt
@@ -19,7 +19,7 @@ class TransactionSerializerDBConverter : Converter {
val row = OutboundRow()
with(row) {
put("hash", Parameter.from(block.hash))
- put("public_key", Parameter.from(block.publicKey))
+ put("public_key", Parameter.from(block.address.publicKey))
put("height", Parameter.from(block.height.value.toBigInteger()))
put("block_type", Parameter.from(block.type))
put("timestamp", Parameter.from(block.timestamp.toJavaInstant()))
diff --git a/src/main/kotlin/cash/atto/node/convertion/UncheckedTransactionConverter.kt b/src/main/kotlin/cash/atto/node/convertion/UncheckedTransactionConverter.kt
index 430d442d..fa2f9914 100644
--- a/src/main/kotlin/cash/atto/node/convertion/UncheckedTransactionConverter.kt
+++ b/src/main/kotlin/cash/atto/node/convertion/UncheckedTransactionConverter.kt
@@ -22,7 +22,7 @@ class UncheckedTransactionSerializerDBConverter : Converter AttoAmount = { it.weight },
) {
private val transactionElectionMap = HashMap()
- private val voterChangeMap = HashMap()
- private val latestVoteTimestampMap = HashMap()
+ private val voterStates = HashMap()
internal fun snapshot(): PublicKeyHeightElection {
val minimalWeight = minimalConfirmationWeightProvider()
@@ -296,8 +296,7 @@ class PublicKeyHeightElection(
copy.votes.putAll(election.votes)
snapshot.transactionElectionMap[hash] = copy
}
- snapshot.voterChangeMap.putAll(voterChangeMap)
- snapshot.latestVoteTimestampMap.putAll(latestVoteTimestampMap)
+ snapshot.voterStates.putAll(voterStates)
return snapshot
}
@@ -319,8 +318,8 @@ class PublicKeyHeightElection(
transactionElectionMap[vote.blockHash]
?: return false
- val latestVoteTimestamp = latestVoteTimestampMap[vote.publicKey]
- if (latestVoteTimestamp != null && vote.timestamp <= latestVoteTimestamp) {
+ val previous = voterStates[vote.publicKey]
+ if (previous != null && vote.timestamp <= previous.latestVoteTimestamp) {
return false
}
@@ -328,23 +327,15 @@ class PublicKeyHeightElection(
return false
}
- latestVoteTimestampMap[vote.publicKey] = vote.timestamp
-
- val oldChange = voterChangeMap[vote.publicKey]
-
- if (oldChange?.blockHash == vote.blockHash) {
- return true
- }
-
- val newChange =
- if (oldChange != null) {
- transactionElectionMap[oldChange.blockHash]!!.remove(vote.publicKey)
- VoterChange(vote.blockHash, Instant.now())
+ val lastChangeAt =
+ if (previous != null && previous.blockHash != vote.blockHash) {
+ transactionElectionMap[previous.blockHash]!!.remove(vote.publicKey)
+ Instant.now()
} else {
- VoterChange(vote.blockHash, Instant.MIN)
+ previous?.lastChangeAt ?: Instant.MIN
}
- voterChangeMap[vote.publicKey] = newChange
+ voterStates[vote.publicKey] = VoterState(vote.blockHash, vote.timestamp, lastChangeAt)
return true
}
@@ -364,7 +355,7 @@ class PublicKeyHeightElection(
val leader = getProvisionalLeader()
val recentlyChanged =
- voterChangeMap.entries
+ voterStates.entries
.asSequence()
.filter { it.value.lastChangeAt > Instant.now().minus(ELECTION_STABILITY_MINIMAL_TIME) }
.map { it.key }
diff --git a/src/main/kotlin/cash/atto/node/election/ElectionVoter.kt b/src/main/kotlin/cash/atto/node/election/ElectionVoter.kt
index a67b399f..b262cc49 100644
--- a/src/main/kotlin/cash/atto/node/election/ElectionVoter.kt
+++ b/src/main/kotlin/cash/atto/node/election/ElectionVoter.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoSignedVote
@@ -279,8 +280,7 @@ class ElectionVoter(
val vote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = thisNode.algorithm,
- publicKey = thisNode.publicKey,
+ address = AttoAddress(thisNode.algorithm, thisNode.publicKey),
blockAlgorithm = transaction.algorithm,
blockHash = transaction.hash,
timestamp = timestamp.toAtto(),
diff --git a/src/main/kotlin/cash/atto/node/network/HandshakeProtocol.kt b/src/main/kotlin/cash/atto/node/network/HandshakeProtocol.kt
new file mode 100644
index 00000000..fd870997
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/network/HandshakeProtocol.kt
@@ -0,0 +1,134 @@
+package cash.atto.node.network
+
+import cash.atto.commons.AttoChallenge
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoSigner
+import cash.atto.commons.fromHexToByteArray
+import cash.atto.node.transaction.Transaction
+import cash.atto.protocol.AttoNode
+import io.github.oshai.kotlinlogging.KotlinLogging
+import java.net.URI
+
+/** Owns the peer challenge exchange; transport deadlines and connection attempts stay with the processor. */
+internal class HandshakeProtocol(
+ private val genesisTransaction: Transaction,
+ private val thisNode: AttoNode,
+ private val signer: AttoSigner,
+) {
+ private val logger = KotlinLogging.logger {}
+
+ suspend fun prepareResponse(
+ remoteHost: String,
+ counterResponse: CounterChallengeResponse,
+ ): PreparedHandshake? {
+ val challenge = counterResponse.challenge
+ val publicUri = ChallengeStore.remove(challenge)
+ if (publicUri == null) {
+ logger.trace { "Received invalid challenge request from $remoteHost $counterResponse" }
+ return null
+ }
+
+ val node = counterResponse.node
+ if (node.publicUri != publicUri) {
+ logger.trace { "Node publicUri ${node.publicUri} doesn't match expected $publicUri from $remoteHost" }
+ return null
+ }
+
+ if (counterResponse.genesis != genesisTransaction.hash) {
+ logger.trace { "Received mismatched genesis hash from $publicUri $remoteHost $counterResponse" }
+ return null
+ }
+
+ if (!counterResponse.signature.isValid(node.publicKey, challengeHash(node, challenge, counterResponse.timestamp))) {
+ logger.trace { "Received invalid signature from server $remoteHost $counterResponse" }
+ return null
+ }
+
+ val counterChallenge = counterResponse.counterChallenge
+ if (!isChallengePrefixValid(counterChallenge)) {
+ logger.trace {
+ "Received invalid challenge prefix request from $publicUri $remoteHost " +
+ "$counterResponse"
+ }
+ return null
+ }
+
+ logger.trace { "Challenge $challenge validated successfully" }
+
+ val timestamp = AttoInstant.now()
+ val response =
+ ChallengeResponse(
+ thisNode,
+ timestamp,
+ signer.sign(AttoChallenge(counterChallenge.fromHexToByteArray()), timestamp),
+ )
+ return PreparedHandshake(publicUri, node, response)
+ }
+
+ suspend fun createCounterResponse(
+ challenge: String,
+ counterChallenge: String,
+ timestamp: AttoInstant,
+ ): CounterChallengeResponse =
+ CounterChallengeResponse(
+ challenge,
+ genesisTransaction.hash,
+ thisNode,
+ timestamp,
+ signer.sign(AttoChallenge(challenge.fromHexToByteArray()), timestamp),
+ counterChallenge,
+ )
+
+ suspend fun authenticateResponse(
+ remoteHost: String,
+ publicUri: URI,
+ counterChallenge: String?,
+ response: ChallengeResponse,
+ ): AttoNode? {
+ if (counterChallenge == null || ChallengeStore.remove(counterChallenge) == null) {
+ logger.trace { "Received invalid challenge response from $publicUri $remoteHost $response" }
+ return null
+ }
+
+ val node = response.node
+ if (node.publicUri != publicUri) {
+ logger.trace { "Node publicUri ${node.publicUri} doesn't match header $publicUri from $remoteHost" }
+ return null
+ }
+ if (!response.signature.isValid(node.publicKey, challengeHash(node, counterChallenge, response.timestamp))) {
+ logger.trace { "Received invalid signature from client $remoteHost $response" }
+ return null
+ }
+ return node
+ }
+
+ fun isChallengePrefixValid(value: String): Boolean {
+ val challenge = value.fromHexToByteArray()
+ if (challenge.size <= ChallengeStore.CHALLENGE_SIZE) {
+ return false
+ }
+
+ val prefixEnd = challenge.size - ChallengeStore.CHALLENGE_SIZE
+ val url = challenge.sliceArray(0 until prefixEnd).toString(Charsets.UTF_8)
+ return url == thisNode.publicUri.toString()
+ }
+
+ private fun challengeHash(
+ node: AttoNode,
+ challenge: String,
+ timestamp: AttoInstant,
+ ): AttoHash =
+ AttoHash.hash(
+ 64,
+ node.publicKey.value,
+ challenge.fromHexToByteArray(),
+ timestamp.toByteArray(),
+ )
+}
+
+internal data class PreparedHandshake(
+ val publicUri: URI,
+ val node: AttoNode,
+ val response: ChallengeResponse,
+)
diff --git a/src/main/kotlin/cash/atto/node/network/NetworkProcessor.kt b/src/main/kotlin/cash/atto/node/network/NetworkProcessor.kt
index 42ae5337..5a15707a 100644
--- a/src/main/kotlin/cash/atto/node/network/NetworkProcessor.kt
+++ b/src/main/kotlin/cash/atto/node/network/NetworkProcessor.kt
@@ -1,10 +1,7 @@
package cash.atto.node.network
-import cash.atto.commons.AttoChallenge
-import cash.atto.commons.AttoHash
import cash.atto.commons.AttoInstant
import cash.atto.commons.AttoSigner
-import cash.atto.commons.fromHexToByteArray
import cash.atto.node.CacheSupport
import cash.atto.node.network.guardian.Guardian
import cash.atto.node.network.guardian.InboundConnectionDecision
@@ -68,9 +65,9 @@ private data class InboundPeerHeaders(
@Component
class NetworkProcessor(
- private val genesisTransaction: Transaction,
+ genesisTransaction: Transaction,
private val thisNode: AttoNode,
- private val signer: AttoSigner,
+ signer: AttoSigner,
environment: Environment,
private val networkProperties: NetworkProperties,
private val peerUriValidator: PeerUriValidator,
@@ -81,6 +78,7 @@ class NetworkProcessor(
private val peerClient: PeerNettyClient,
) : CacheSupport {
private val logger = KotlinLogging.logger {}
+ private val handshakeProtocol = HandshakeProtocol(genesisTransaction, thisNode, signer)
companion object {
const val PUBLIC_URI_HEADER = "Atto-Public-Uri"
@@ -166,60 +164,10 @@ class NetworkProcessor(
MAX_COUNTER_CHALLENGE_RESPONSE_SIZE_BYTES,
request.requestHeaders().get(HttpHeaderNames.CONTENT_LENGTH)?.toLongOrNull(),
)
- val challenge = counterResponse.challenge
-
- val publicUri = ChallengeStore.remove(challenge)
- if (publicUri == null) {
- logger.trace { "Received invalid challenge request from $remoteHost $counterResponse" }
- return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
- }
-
- val node = counterResponse.node
- if (node.publicUri != publicUri) {
- logger.trace { "Node publicUri ${node.publicUri} doesn't match expected $publicUri from $remoteHost" }
- return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
- }
-
- if (counterResponse.genesis != genesisTransaction.hash) {
- logger.trace { "Received mismatched genesis hash from $publicUri $remoteHost $counterResponse" }
- return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
- }
-
- val counterTimestamp = counterResponse.timestamp
- val hash =
- AttoHash.hash(
- 64,
- node.publicKey.value,
- challenge.fromHexToByteArray(),
- counterTimestamp.toByteArray(),
- )
-
- val signature = counterResponse.signature
- if (!signature.isValid(node.publicKey, hash)) {
- logger.trace { "Received invalid signature from server $remoteHost $counterResponse" }
- return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
- }
-
- val counterChallenge = counterResponse.counterChallenge
- if (!counterChallenge.isChallengePrefixValid()) {
- logger.trace {
- "Received invalid challenge prefix request from $publicUri $remoteHost " +
- "$counterResponse"
- }
- return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
- }
-
- logger.trace { "Challenge $challenge validated successfully" }
-
- val timestamp = AttoInstant.now()
- val response =
- ChallengeResponse(
- thisNode,
- timestamp,
- signer.sign(AttoChallenge(counterChallenge.fromHexToByteArray()), timestamp),
- )
-
- return InboundHandshakePreparation.Accepted(publicUri, node, response)
+ val handshake =
+ handshakeProtocol.prepareResponse(remoteHost, counterResponse)
+ ?: return InboundHandshakePreparation.Rejected(HttpResponseStatus.BAD_REQUEST)
+ return InboundHandshakePreparation.Accepted(handshake.publicUri, handshake.node, handshake.response)
}
private suspend fun HttpServerResponse.finishInboundHandshake(handshake: InboundHandshakePreparation.Accepted) {
@@ -283,7 +231,7 @@ class NetworkProcessor(
}
logger.trace { "Headers received: publicUri=$publicUri, challenge=$challengeHeader" }
- if (!challengeHeader.isChallengePrefixValid()) {
+ if (!handshakeProtocol.isChallengePrefixValid(challengeHeader)) {
logger.trace { "Received invalid challenge prefix request from $publicUri $remoteHost" }
return null
}
@@ -309,14 +257,7 @@ class NetworkProcessor(
handshakeCallbackService.post(remoteHost, publicUri) {
val generatedCounterChallenge = ChallengeStore.generate(publicUri)
counterChallenge = generatedCounterChallenge
- CounterChallengeResponse(
- headers.challenge,
- genesisTransaction.hash,
- thisNode,
- timestamp,
- signer.sign(AttoChallenge(headers.challenge.fromHexToByteArray()), timestamp),
- generatedCounterChallenge,
- )
+ handshakeProtocol.createCounterResponse(headers.challenge, generatedCounterChallenge, timestamp)
}
val result = callbackResult as? HandshakeCallbackResult.Completed ?: return null
authenticatedNode = validateInboundCallback(remoteHost, publicUri, counterChallenge, result)
@@ -344,28 +285,7 @@ class NetworkProcessor(
logger.trace { "Received empty challenge response from $publicUri $remoteHost" }
return null
}
- if (counterChallenge == null || ChallengeStore.remove(counterChallenge) == null) {
- logger.trace { "Received invalid challenge response from $publicUri $remoteHost $response" }
- return null
- }
-
- val node = response.node
- if (node.publicUri != publicUri) {
- logger.trace { "Node publicUri ${node.publicUri} doesn't match header $publicUri from $remoteHost" }
- return null
- }
- val counterHash =
- AttoHash.hash(
- 64,
- node.publicKey.value,
- counterChallenge.fromHexToByteArray(),
- response.timestamp.toByteArray(),
- )
- if (!response.signature.isValid(node.publicKey, counterHash)) {
- logger.trace { "Received invalid signature from client $remoteHost $response" }
- return null
- }
- return node
+ return handshakeProtocol.authenticateResponse(remoteHost, publicUri, counterChallenge, response)
}
override fun clear() {
@@ -533,18 +453,5 @@ class NetworkProcessor(
}
}
- private fun String.isChallengePrefixValid(): Boolean {
- val challenge = this.fromHexToByteArray()
-
- if (challenge.size <= ChallengeStore.CHALLENGE_SIZE) {
- return false
- }
-
- val prefixEnd = challenge.size - ChallengeStore.CHALLENGE_SIZE
- val url = challenge.sliceArray(0 until prefixEnd).toString(Charsets.UTF_8)
-
- return url == thisNode.publicUri.toString()
- }
-
private fun String.toUriOrNull(): URI? = runCatching { URI(this) }.getOrNull()
}
diff --git a/src/main/kotlin/cash/atto/node/receivable/LegacyReceivableResponse.kt b/src/main/kotlin/cash/atto/node/receivable/LegacyReceivableResponse.kt
new file mode 100644
index 00000000..110658c6
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/receivable/LegacyReceivableResponse.kt
@@ -0,0 +1,44 @@
+package cash.atto.node.receivable
+
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoReceivable
+import cash.atto.commons.AttoVersion
+import cash.atto.node.LegacyAmountSerializer
+import cash.atto.node.LegacyInstantSerializer
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class LegacyReceivableResponse(
+ val network: AttoNetwork,
+ val hash: AttoHash,
+ val version: AttoVersion,
+ val algorithm: AttoAlgorithm,
+ val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ val timestamp: AttoInstant,
+ val receiverAlgorithm: AttoAlgorithm,
+ val receiverPublicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val amount: AttoAmount,
+)
+
+fun AttoReceivable.toLegacyResponse(): LegacyReceivableResponse =
+ LegacyReceivableResponse(
+ network = network,
+ hash = hash,
+ version = version,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ timestamp = timestamp,
+ receiverAlgorithm = receiverAddress.algorithm,
+ receiverPublicKey = receiverAddress.publicKey,
+ amount = amount,
+ )
diff --git a/src/main/kotlin/cash/atto/node/receivable/Receivable.kt b/src/main/kotlin/cash/atto/node/receivable/Receivable.kt
index 8cd0bc91..7c485fc3 100644
--- a/src/main/kotlin/cash/atto/node/receivable/Receivable.kt
+++ b/src/main/kotlin/cash/atto/node/receivable/Receivable.kt
@@ -1,5 +1,6 @@
package cash.atto.node.receivable
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -36,11 +37,9 @@ data class Receivable(
network = network,
hash = hash,
version = version,
- algorithm = algorithm,
- publicKey = publicKey,
+ address = AttoAddress(algorithm, publicKey),
timestamp = timestamp.toAtto(),
- receiverAlgorithm = receiverAlgorithm,
- receiverPublicKey = receiverPublicKey,
+ receiverAddress = AttoAddress(receiverAlgorithm, receiverPublicKey),
amount = amount,
)
}
@@ -50,11 +49,11 @@ fun AttoReceivable.toReceivable(): Receivable =
network = network,
hash = hash,
version = version,
- algorithm = algorithm,
- publicKey = publicKey,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
timestamp = timestamp.toJavaInstant(),
- receiverAlgorithm = receiverAlgorithm,
- receiverPublicKey = receiverPublicKey,
+ receiverAlgorithm = receiverAddress.algorithm,
+ receiverPublicKey = receiverAddress.publicKey,
amount = amount,
)
diff --git a/src/main/kotlin/cash/atto/node/receivable/ReceivableController.kt b/src/main/kotlin/cash/atto/node/receivable/ReceivableController.kt
index cd08f3a8..80ffb849 100644
--- a/src/main/kotlin/cash/atto/node/receivable/ReceivableController.kt
+++ b/src/main/kotlin/cash/atto/node/receivable/ReceivableController.kt
@@ -1,41 +1,18 @@
package cash.atto.node.receivable
import cash.atto.commons.AttoAddress
-import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
-import cash.atto.commons.AttoHash
-import cash.atto.commons.AttoInstant
import cash.atto.commons.AttoPublicKey
import cash.atto.commons.AttoReceivable
import cash.atto.commons.node.AccountSearch
-import io.github.oshai.kotlinlogging.KotlinLogging
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
-import kotlinx.coroutines.CompletableDeferred
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.coroutineScope
-import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.asFlow
-import kotlinx.coroutines.flow.consumeAsFlow
-import kotlinx.coroutines.flow.emitAll
-import kotlinx.coroutines.flow.filter
-import kotlinx.coroutines.flow.filterNot
-import kotlinx.coroutines.flow.flatMapConcat
-import kotlinx.coroutines.flow.flatMapMerge
-import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.onCompletion
-import kotlinx.coroutines.flow.onEach
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.flow.onSubscription
-import kotlinx.coroutines.flow.produceIn
-import org.springframework.context.event.EventListener
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
@@ -54,20 +31,10 @@ import org.springframework.web.bind.annotation.RestController
"it becomes a \"receivable\" until the recipient explicitly receives it.",
)
class ReceivableController(
- val repository: ReceivableRepository,
+ private val queries: ReceivableQueries,
) {
- private val logger = KotlinLogging.logger {}
-
- private val receivableFlow = MutableSharedFlow()
-
- @EventListener
- suspend fun process(receivableSaved: ReceivableSaved) {
- receivableFlow.emit(receivableSaved.receivable)
- }
-
- @OptIn(ExperimentalCoroutinesApi::class)
- @PostMapping("/accounts/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamReceivablesByAddresses",
summary = "Stream all receivables for multiple addresses",
responses = [
ApiResponse(
@@ -80,80 +47,59 @@ class ReceivableController(
),
],
)
+ @PostMapping("/v2/accounts/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
suspend fun stream(
@RequestBody search: AccountSearch,
@RequestParam(defaultValue = "1") minAmount: AttoAmount,
- ): Flow {
- val publicKeys = search.addresses.map { it.publicKey }.toSet()
- val databaseReceivables =
- publicKeys
- .chunked(1000)
- .asFlow()
- .flatMapConcat { repository.findAllDesc(it, minAmount) }
-
- val receivables =
- flow {
- coroutineScope {
- val subscribed = CompletableDeferred()
- val liveReceivables =
- receivableFlow
- .onSubscription { subscribed.complete(Unit) }
- .filter { it.receiverPublicKey in publicKeys }
- .filter { it.amount >= minAmount }
- .produceIn(this)
-
- try {
- val databaseHashes = HashSet()
-
- // Wait for the live subscription before scanning so concurrent commits cannot fall into a gap.
- subscribed.await()
- emitAll(databaseReceivables.onEach { databaseHashes.add(it.hash) })
-
- // Retain snapshot hashes to suppress delayed notifications without caching live history.
- emitAll(liveReceivables.consumeAsFlow().filterNot { it.hash in databaseHashes })
- } finally {
- liveReceivables.cancel()
- }
- }
- }
+ ): Flow = queries.stream(search, minAmount)
- return receivables
- .map { it.toAttoReceivable() }
- .flatMapMerge { receivable ->
- val duration = receivable.timestamp - AttoInstant.now()
+ @Operation(
+ operationId = "streamReceivablesByAddress",
+ summary = "Stream receivables by address",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [Content(schema = Schema(implementation = AttoReceivable::class))],
+ ),
+ ],
+ )
+ @GetMapping("/v2/accounts/{address}/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(
+ @PathVariable address: AttoAddress,
+ @RequestParam(defaultValue = "1") minAmount: AttoAmount,
+ ): Flow = stream(address.publicKey, minAmount)
- if (duration.isPositive()) {
- flow {
- delay(duration)
- emit(receivable)
- }
- } else {
- flowOf(receivable)
- }
- }.onStart { logger.trace { "Started streaming receivables for addresses $search" } }
- .onCompletion { logger.trace { "Stopped streaming receivables for addresses $search" } }
- }
+ suspend fun stream(
+ @PathVariable publicKey: AttoPublicKey,
+ @RequestParam(defaultValue = "1") minAmount: AttoAmount,
+ ): Flow = queries.stream(publicKey, minAmount)
- @OptIn(ExperimentalCoroutinesApi::class)
- @GetMapping("/accounts/{publicKey}/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ @Hidden
@Operation(
- summary = "Stream all receivables",
+ operationId = "streamLegacyReceivablesByAddresses",
+ summary = "Stream all receivables for multiple addresses",
responses = [
ApiResponse(
responseCode = "200",
content = [
Content(
- schema = Schema(implementation = AttoReceivable::class),
+ schema = Schema(implementation = LegacyReceivableResponse::class),
),
],
),
],
)
- suspend fun stream(
+ @PostMapping("/accounts/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
+ @RequestBody search: AccountSearch,
+ @RequestParam(defaultValue = "1") minAmount: AttoAmount,
+ ): Flow = stream(search, minAmount).map { it.toLegacyResponse() }
+
+ @Hidden
+ @Operation(operationId = "streamLegacyReceivablesByPublicKey")
+ @GetMapping("/accounts/{publicKey}/receivables/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
@PathVariable publicKey: AttoPublicKey,
@RequestParam(defaultValue = "1") minAmount: AttoAmount,
- ): Flow {
- val address = AttoAddress(AttoAlgorithm.V1, publicKey)
- return stream(AccountSearch(listOf(address)), minAmount)
- }
+ ): Flow = stream(publicKey, minAmount).map { it.toLegacyResponse() }
}
diff --git a/src/main/kotlin/cash/atto/node/receivable/ReceivableQueries.kt b/src/main/kotlin/cash/atto/node/receivable/ReceivableQueries.kt
new file mode 100644
index 00000000..36c9b1c4
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/receivable/ReceivableQueries.kt
@@ -0,0 +1,117 @@
+package cash.atto.node.receivable
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoReceivable
+import cash.atto.commons.node.AccountSearch
+import io.github.oshai.kotlinlogging.KotlinLogging
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asFlow
+import kotlinx.coroutines.flow.consumeAsFlow
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.filterNot
+import kotlinx.coroutines.flow.flatMapConcat
+import kotlinx.coroutines.flow.flatMapMerge
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onCompletion
+import kotlinx.coroutines.flow.onEach
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.onSubscription
+import kotlinx.coroutines.flow.produceIn
+import org.springframework.context.event.EventListener
+import org.springframework.stereotype.Component
+
+@Component
+class ReceivableQueries(
+ private val repository: ReceivableRepository,
+) {
+ private val logger = KotlinLogging.logger {}
+
+ private val receivableFlow = MutableSharedFlow()
+
+ @EventListener
+ suspend fun process(receivableSaved: ReceivableSaved) {
+ receivableFlow.emit(receivableSaved.receivable)
+ }
+
+ @OptIn(ExperimentalCoroutinesApi::class)
+ suspend fun stream(
+ search: AccountSearch,
+ minAmount: AttoAmount,
+ ): Flow {
+ val publicKeys = search.addresses.map { it.publicKey }.toSet()
+ val databaseReceivables =
+ publicKeys
+ .chunked(1000)
+ .asFlow()
+ .flatMapConcat { repository.findAllDesc(it, minAmount) }
+
+ val receivables =
+ flow {
+ coroutineScope {
+ val subscribed = CompletableDeferred()
+ val liveReceivables =
+ receivableFlow
+ .onSubscription { subscribed.complete(Unit) }
+ .filter { it.receiverPublicKey in publicKeys }
+ .filter { it.amount >= minAmount }
+ .produceIn(this)
+
+ try {
+ val databaseHashes = HashSet()
+
+ // Wait for the live subscription before scanning so concurrent commits cannot fall into a gap.
+ subscribed.await()
+ emitAll(databaseReceivables.onEach { databaseHashes.add(it.hash) })
+
+ // Retain snapshot hashes to suppress delayed notifications without caching live history.
+ emitAll(liveReceivables.consumeAsFlow().filterNot { it.hash in databaseHashes })
+ } finally {
+ liveReceivables.cancel()
+ }
+ }
+ }
+
+ return receivables
+ .map { it.toAttoReceivable() }
+ .flatMapMerge { receivable ->
+ val duration = receivable.timestamp - AttoInstant.now()
+
+ if (duration.isPositive()) {
+ flow {
+ delay(duration)
+ emit(receivable)
+ }
+ } else {
+ flowOf(receivable)
+ }
+ }.onStart { logger.trace { "Started streaming receivables for addresses $search" } }
+ .onCompletion { logger.trace { "Stopped streaming receivables for addresses $search" } }
+ }
+
+ suspend fun stream(
+ address: AttoAddress,
+ minAmount: AttoAmount,
+ ): Flow = stream(address.publicKey, minAmount)
+
+ @OptIn(ExperimentalCoroutinesApi::class)
+ suspend fun stream(
+ publicKey: AttoPublicKey,
+ minAmount: AttoAmount,
+ ): Flow {
+ val address = AttoAddress(AttoAlgorithm.V1, publicKey)
+ return stream(AccountSearch(listOf(address)), minAmount)
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/signature/NettyRemoteSigner.kt b/src/main/kotlin/cash/atto/node/signature/NettyRemoteSigner.kt
index 2fd1c2a7..04e9f3db 100644
--- a/src/main/kotlin/cash/atto/node/signature/NettyRemoteSigner.kt
+++ b/src/main/kotlin/cash/atto/node/signature/NettyRemoteSigner.kt
@@ -46,23 +46,23 @@ class NettyRemoteSigner(
override suspend fun sign(block: AttoBlock): AttoSignature =
transport.operation {
- checkPublicKey(block.publicKey)
+ checkPublicKey(block.address.publicKey)
val signature =
retrying("sign $block") {
request("blocks", json.encodeToString(BlockSignatureRequest(block)), 1).signature
}
- if (!signature.isValid(block.publicKey, block.hash)) throw RemoteSignerInvalidSignatureException("block")
+ if (!signature.isValid(block.address.publicKey, block.hash)) throw RemoteSignerInvalidSignatureException("block")
signature
}
override suspend fun sign(vote: AttoVote): AttoSignature =
transport.operation {
- checkPublicKey(vote.publicKey)
+ checkPublicKey(vote.address.publicKey)
val signature =
retrying("sign $vote") {
request("votes", json.encodeToString(VoteSignatureRequest(vote)), 1).signature
}
- if (!signature.isValid(vote.publicKey, vote.hash)) throw RemoteSignerInvalidSignatureException("vote")
+ if (!signature.isValid(vote.address.publicKey, vote.hash)) throw RemoteSignerInvalidSignatureException("vote")
signature
}
diff --git a/src/main/kotlin/cash/atto/node/stream/NodeStreamDispatcher.kt b/src/main/kotlin/cash/atto/node/stream/NodeStreamDispatcher.kt
new file mode 100644
index 00000000..078e8694
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/stream/NodeStreamDispatcher.kt
@@ -0,0 +1,223 @@
+package cash.atto.node.stream
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.node.AccountSearch
+import cash.atto.commons.node.AttoStreamMethod
+import cash.atto.commons.node.AttoStreamProtocol
+import cash.atto.commons.node.AttoStreamRequest
+import cash.atto.commons.node.HeightSearch
+import cash.atto.commons.node.stream.server.AttoStreamMember
+import cash.atto.commons.node.stream.server.AttoStreamPlan
+import cash.atto.commons.spring.AttoStreamRequestTarget
+import cash.atto.node.account.AccountQueries
+import cash.atto.node.account.entry.AccountEntryQueries
+import cash.atto.node.account.validateRanges
+import cash.atto.node.receivable.ReceivableQueries
+import cash.atto.node.transaction.TransactionQueries
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.encodeToJsonElement
+import org.springframework.beans.factory.annotation.Qualifier
+import org.springframework.http.HttpStatus
+import org.springframework.stereotype.Component
+import org.springframework.web.server.ResponseStatusException
+
+/** Translates the public stream protocol into the same query operations used by HTTP. */
+@Component
+class NodeStreamDispatcher(
+ private val accounts: AccountQueries,
+ private val receivables: ReceivableQueries,
+ private val entries: AccountEntryQueries,
+ private val transactions: TransactionQueries,
+ @param:Qualifier("publicApiJson") private val json: Json,
+) {
+ suspend fun plan(
+ request: AttoStreamRequest,
+ mutable: Boolean,
+ ): AttoStreamPlan {
+ if (!mutable) {
+ return AttoStreamPlan(
+ mapOf(
+ "stream" to AttoStreamMember(AttoStreamProtocol.encodeRequest(request)) { dispatch(request) },
+ ),
+ )
+ }
+ request.requireMethod(AttoStreamMethod.POST)
+ val target = AttoStreamRequestTarget(request.path)
+ val path = target.segments
+ return when (path) {
+ listOf("v2", "accounts", "stream") -> {
+ val search = request.body()
+ AttoStreamPlan(
+ search.addresses.toSet().associate { address ->
+ address.toString() to AttoStreamMember("account") { accounts.stream(AccountSearch(setOf(address))).encoded() }
+ },
+ )
+ }
+
+ listOf("v2", "accounts", "receivables", "stream") -> {
+ val search = request.body()
+ val minAmount = target.minAmount()
+ AttoStreamPlan(
+ search.addresses.toSet().associate { address ->
+ address.toString() to
+ AttoStreamMember("receivables:$minAmount") {
+ receivables.stream(AccountSearch(setOf(address)), minAmount).encoded()
+ }
+ },
+ )
+ }
+
+ listOf("v2", "accounts", "entries", "stream"), listOf("v2", "accounts", "transactions", "stream") -> {
+ val search = request.body()
+ search.validateRanges()
+ if (search.search
+ .map { it.address }
+ .distinct()
+ .size != search.search.size
+ ) {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Mutable stream addresses must be unique")
+ }
+ AttoStreamPlan(
+ search.search.associate { range ->
+ range.address.toString() to
+ AttoStreamMember("${path[2]}:${range.fromHeight}:${range.toHeight}") {
+ val memberSearch = HeightSearch(listOf(range))
+ if (path[2] == "entries") {
+ entries.streamMultiple(memberSearch).encoded()
+ } else {
+ transactions.streamMultiple(memberSearch).encoded()
+ }
+ }
+ },
+ )
+ }
+
+ else -> {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "This stream does not support membership updates")
+ }
+ }
+ }
+
+ suspend fun dispatch(request: AttoStreamRequest): Flow {
+ val target = AttoStreamRequestTarget(request.path)
+ val path = target.segments
+ return when {
+ path == listOf("v2", "accounts", "stream") -> {
+ when (request.method) {
+ AttoStreamMethod.GET -> accounts.stream().encoded()
+ AttoStreamMethod.POST -> accounts.stream(request.body()).encoded()
+ }
+ }
+
+ path == listOf("v2", "accounts", "receivables", "stream") -> {
+ request.requireMethod(AttoStreamMethod.POST)
+ receivables.stream(request.body(), target.minAmount()).encoded()
+ }
+
+ path == listOf("v2", "accounts", "entries", "stream") -> {
+ when (request.method) {
+ AttoStreamMethod.GET -> entries.stream().encoded()
+ AttoStreamMethod.POST -> entries.streamMultiple(request.body()).encoded()
+ }
+ }
+
+ path == listOf("v2", "accounts", "transactions", "stream") -> {
+ request.requireMethod(AttoStreamMethod.POST)
+ transactions.streamMultiple(request.body()).encoded()
+ }
+
+ path == listOf("v2", "transactions", "stream") -> {
+ request.requireMethod(AttoStreamMethod.GET)
+ transactions.stream().encoded()
+ }
+
+ path.size == 4 && path.take(2) == listOf("v2", "transactions") && path.last() == "stream" -> {
+ request.requireMethod(AttoStreamMethod.GET)
+ transactions.stream(bind { AttoHash.parse(path[2]) }).encoded()
+ }
+
+ path.size == 5 && path.take(3) == listOf("v2", "accounts", "entries") && path.last() == "stream" -> {
+ request.requireMethod(AttoStreamMethod.GET)
+ entries.stream(bind { AttoHash.parse(path[3]) }).encoded()
+ }
+
+ path.size in 4..5 && path.take(2) == listOf("v2", "accounts") && path.last() == "stream" -> {
+ if (path.size == 5 && path[3] !in setOf("receivables", "entries", "transactions")) {
+ throw ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown stream operation")
+ }
+ request.requireMethod(AttoStreamMethod.GET)
+ val address = bind { AttoAddress.parse(path[2]) }
+ when {
+ path.size == 4 -> {
+ accounts.stream(address).encoded()
+ }
+
+ path[3] == "receivables" -> {
+ receivables.stream(address, target.minAmount()).encoded()
+ }
+
+ path[3] == "entries" -> {
+ entries.stream(address, target.fromHeight(), target.toHeight()).encoded()
+ }
+
+ path[3] == "transactions" -> {
+ transactions.stream(address, target.fromHeight(), target.toHeight() ?: AttoHeight.MAX).encoded()
+ }
+
+ else -> {
+ throw ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown stream operation")
+ }
+ }
+ }
+
+ else -> {
+ throw ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown stream operation")
+ }
+ }
+ }
+
+ private fun AttoStreamRequest.requireMethod(expected: AttoStreamMethod) {
+ if (method != expected) {
+ throw ResponseStatusException(HttpStatus.METHOD_NOT_ALLOWED, "Stream operation requires $expected")
+ }
+ }
+
+ private inline fun AttoStreamRequest.body(): T =
+ bind {
+ val value = body ?: throw IllegalArgumentException("Missing stream request body")
+ json.decodeFromJsonElement(value)
+ }
+
+ private fun AttoStreamRequestTarget.scalar(name: String): String? {
+ if (queryValues(name).size > 1) throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Repeated stream parameter: $name")
+ return query(name)
+ }
+
+ private fun AttoStreamRequestTarget.minAmount(): AttoAmount = bind { AttoAmount(scalar("minAmount").orDefault("1").toULong()) }
+
+ private fun AttoStreamRequestTarget.fromHeight(): AttoHeight = bind { AttoHeight(scalar("fromHeight").orDefault("1").toULong()) }
+
+ private fun AttoStreamRequestTarget.toHeight(): AttoHeight? =
+ bind { scalar("toHeight")?.takeIf { it.isNotEmpty() }?.let { AttoHeight(it.toULong()) } }
+
+ private fun String?.orDefault(default: String): String = this?.takeIf { it.isNotEmpty() } ?: default
+
+ private inline fun Flow.encoded(): Flow = map { json.encodeToJsonElement(it) }
+
+ private inline fun bind(block: () -> T): T =
+ try {
+ block()
+ } catch (exception: SerializationException) {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid stream operation parameters", exception)
+ } catch (exception: IllegalArgumentException) {
+ throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid stream operation parameters", exception)
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfiguration.kt b/src/main/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfiguration.kt
new file mode 100644
index 00000000..0859e974
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfiguration.kt
@@ -0,0 +1,32 @@
+package cash.atto.node.stream
+
+import cash.atto.commons.node.AttoStreamProtocol
+import cash.atto.commons.spring.AttoStreamWebSocketHandler
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping
+import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService
+import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter
+import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy
+import reactor.netty.http.server.WebsocketServerSpec
+
+@Configuration(proxyBeanMethods = false)
+class NodeStreamWebSocketConfiguration {
+ @Bean
+ fun publicStreamHandlerMapping(dispatcher: NodeStreamDispatcher): SimpleUrlHandlerMapping =
+ SimpleUrlHandlerMapping(
+ mapOf(
+ AttoStreamProtocol.PATH to AttoStreamWebSocketHandler({ request, _, mutable -> dispatcher.plan(request, mutable) }),
+ ),
+ -1,
+ )
+
+ @Bean
+ fun publicStreamWebSocketHandlerAdapter(): WebSocketHandlerAdapter {
+ val strategy =
+ ReactorNettyRequestUpgradeStrategy {
+ WebsocketServerSpec.builder().maxFramePayloadLength(AttoStreamWebSocketHandler.MAX_FRAME_PAYLOAD_LENGTH)
+ }
+ return WebSocketHandlerAdapter(HandshakeWebSocketService(strategy)).apply { order = 1 }
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/time/InstantController.kt b/src/main/kotlin/cash/atto/node/time/InstantController.kt
index 5448298c..dbc708c9 100644
--- a/src/main/kotlin/cash/atto/node/time/InstantController.kt
+++ b/src/main/kotlin/cash/atto/node/time/InstantController.kt
@@ -21,7 +21,7 @@ import kotlin.time.ExperimentalTime
class InstantController {
@OptIn(ExperimentalTime::class)
@GetMapping("/{clientInstant}")
- @Operation(summary = "Return time adjustment to send transactions")
+ @Operation(operationId = "getTimeDifference", summary = "Return time adjustment to send transactions")
suspend fun get(
@PathVariable clientInstant: Instant,
): TimeDifferenceResponse {
diff --git a/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionRequest.kt b/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionRequest.kt
new file mode 100644
index 00000000..33c2d046
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionRequest.kt
@@ -0,0 +1,79 @@
+package cash.atto.node.transaction
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoTransaction
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.encoding.Decoder
+import kotlinx.serialization.encoding.Encoder
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonDecoder
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.encodeToJsonElement
+
+@Serializable(with = LegacyTransactionRequestSerializer::class)
+@Schema(implementation = AttoTransaction::class)
+data class LegacyTransactionRequest(
+ val transaction: AttoTransaction,
+)
+
+internal object LegacyTransactionRequestSerializer : KSerializer {
+ override val descriptor = AttoTransaction.serializer().descriptor
+
+ override fun deserialize(decoder: Decoder): LegacyTransactionRequest {
+ val jsonDecoder = decoder as? JsonDecoder ?: throw SerializationException("Legacy transaction requests require JSON")
+ val transaction = jsonDecoder.decodeJsonElement() as? JsonObject ?: throw SerializationException("Expected a transaction object")
+ val block = transaction["block"] as? JsonObject ?: throw SerializationException("Expected a transaction block")
+ val fields = block.toMutableMap()
+ fields.restoreAddress(jsonDecoder.json, "address", "algorithm", "publicKey")
+ when ((block["type"] as? JsonPrimitive)?.content) {
+ "OPEN", "CHANGE" -> {
+ fields.restoreAddress(
+ jsonDecoder.json,
+ "representativeAddress",
+ "representativeAlgorithm",
+ "representativePublicKey",
+ )
+ }
+
+ "SEND" -> {
+ fields.restoreAddress(jsonDecoder.json, "receiverAddress", "receiverAlgorithm", "receiverPublicKey")
+ }
+ }
+ val canonical = JsonObject(transaction + ("block" to JsonObject(fields)))
+ return LegacyTransactionRequest(jsonDecoder.json.decodeFromJsonElement(canonical))
+ }
+
+ override fun serialize(
+ encoder: Encoder,
+ value: LegacyTransactionRequest,
+ ) = encoder.encodeSerializableValue(AttoTransaction.serializer(), value.transaction)
+
+ private fun MutableMap.restoreAddress(
+ json: Json,
+ addressField: String,
+ algorithmField: String,
+ publicKeyField: String,
+ ) {
+ if (!containsKey(addressField)) {
+ val algorithm = get(algorithmField) ?: throw SerializationException("Missing $addressField or $algorithmField")
+ val publicKey = get(publicKeyField) ?: throw SerializationException("Missing $addressField or $publicKeyField")
+ val address =
+ try {
+ AttoAddress(json.decodeFromJsonElement(algorithm), json.decodeFromJsonElement(publicKey))
+ } catch (exception: IllegalArgumentException) {
+ throw SerializationException("Invalid legacy $addressField", exception)
+ }
+ put(addressField, json.encodeToJsonElement(address))
+ }
+ remove(algorithmField)
+ remove(publicKeyField)
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionResponse.kt b/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionResponse.kt
new file mode 100644
index 00000000..10bfeec3
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/transaction/LegacyTransactionResponse.kt
@@ -0,0 +1,264 @@
+package cash.atto.node.transaction
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoBlock
+import cash.atto.commons.AttoBlockType
+import cash.atto.commons.AttoChangeBlock
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoOpenBlock
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoReceiveBlock
+import cash.atto.commons.AttoSendBlock
+import cash.atto.commons.AttoSignature
+import cash.atto.commons.AttoTransaction
+import cash.atto.commons.AttoVersion
+import cash.atto.commons.AttoWork
+import cash.atto.node.LegacyAmountSerializer
+import cash.atto.node.LegacyHeightSerializer
+import cash.atto.node.LegacyInstantSerializer
+import io.swagger.v3.oas.annotations.media.DiscriminatorMapping
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.Transient
+
+@Serializable
+data class LegacyTransactionResponse(
+ val block: LegacyBlock,
+ val signature: AttoSignature,
+ val work: AttoWork,
+)
+
+@Serializable
+@Schema(
+ name = "LegacyBlock",
+ discriminatorProperty = "type",
+ discriminatorMapping = [
+ DiscriminatorMapping(value = "OPEN", schema = LegacyBlock.Open::class),
+ DiscriminatorMapping(value = "RECEIVE", schema = LegacyBlock.Receive::class),
+ DiscriminatorMapping(value = "SEND", schema = LegacyBlock.Send::class),
+ DiscriminatorMapping(value = "CHANGE", schema = LegacyBlock.Change::class),
+ ],
+)
+sealed interface LegacyBlock {
+ @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = ["OPEN", "RECEIVE", "SEND", "CHANGE"])
+ val type: AttoBlockType
+
+ val network: AttoNetwork
+ val version: AttoVersion
+ val algorithm: AttoAlgorithm
+ val publicKey: AttoPublicKey
+ val address: AttoAddress
+
+ @get:Schema(description = "Height of the block (unsigned 64-bit)")
+ val height: AttoHeight
+ val balance: AttoAmount
+ val timestamp: AttoInstant
+
+ @Serializable
+ @SerialName("OPEN")
+ @Schema(name = "LegacyOpenBlock")
+ data class Open(
+ override val network: AttoNetwork,
+ override val version: AttoVersion,
+ override val algorithm: AttoAlgorithm,
+ override val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ override val balance: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ override val timestamp: AttoInstant,
+ @get:Schema(description = "Algorithm of the send block")
+ val sendHashAlgorithm: AttoAlgorithm,
+ @get:Schema(description = "Hash of the send block (hex)")
+ val sendHash: AttoHash,
+ @get:Schema(description = "Algorithm of the representative")
+ val representativeAlgorithm: AttoAlgorithm,
+ val representativePublicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ override val height: AttoHeight,
+ override val address: AttoAddress,
+ @get:Schema(description = "Address of the representative")
+ val representativeAddress: AttoAddress,
+ ) : LegacyBlock {
+ @Transient
+ @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = ["OPEN"])
+ override val type = AttoBlockType.OPEN
+ }
+
+ @Serializable
+ @SerialName("RECEIVE")
+ @Schema(name = "LegacyReceiveBlock")
+ data class Receive(
+ override val network: AttoNetwork,
+ override val version: AttoVersion,
+ override val algorithm: AttoAlgorithm,
+ override val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ override val height: AttoHeight,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ override val balance: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ override val timestamp: AttoInstant,
+ @get:Schema(description = "Hash of the previous block (hex)")
+ val previous: AttoHash,
+ @get:Schema(description = "Algorithm of the send block")
+ val sendHashAlgorithm: AttoAlgorithm,
+ @get:Schema(description = "Hash of the send block (hex)")
+ val sendHash: AttoHash,
+ override val address: AttoAddress,
+ ) : LegacyBlock {
+ @Transient
+ @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = ["RECEIVE"])
+ override val type = AttoBlockType.RECEIVE
+ }
+
+ @Serializable
+ @SerialName("SEND")
+ @Schema(name = "LegacySendBlock")
+ data class Send(
+ override val network: AttoNetwork,
+ override val version: AttoVersion,
+ override val algorithm: AttoAlgorithm,
+ override val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ override val height: AttoHeight,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ override val balance: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ override val timestamp: AttoInstant,
+ @get:Schema(description = "Hash of the previous block (hex)")
+ val previous: AttoHash,
+ @get:Schema(description = "Algorithm of the receiver")
+ val receiverAlgorithm: AttoAlgorithm,
+ val receiverPublicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val amount: AttoAmount,
+ override val address: AttoAddress,
+ @get:Schema(description = "Address of the receiver")
+ val receiverAddress: AttoAddress,
+ ) : LegacyBlock {
+ @Transient
+ @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = ["SEND"])
+ override val type = AttoBlockType.SEND
+ }
+
+ @Serializable
+ @SerialName("CHANGE")
+ @Schema(name = "LegacyChangeBlock")
+ data class Change(
+ override val network: AttoNetwork,
+ override val version: AttoVersion,
+ override val algorithm: AttoAlgorithm,
+ override val publicKey: AttoPublicKey,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyHeightSerializer::class)
+ override val height: AttoHeight,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ override val balance: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ override val timestamp: AttoInstant,
+ @get:Schema(description = "Hash of the previous block (hex)")
+ val previous: AttoHash,
+ @get:Schema(description = "Algorithm of the representative")
+ val representativeAlgorithm: AttoAlgorithm,
+ val representativePublicKey: AttoPublicKey,
+ override val address: AttoAddress,
+ @get:Schema(description = "Address of the representative")
+ val representativeAddress: AttoAddress,
+ ) : LegacyBlock {
+ @Transient
+ @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = ["CHANGE"])
+ override val type = AttoBlockType.CHANGE
+ }
+}
+
+fun AttoTransaction.toLegacyResponse(): LegacyTransactionResponse = LegacyTransactionResponse(block.toLegacyResponse(), signature, work)
+
+internal fun AttoBlock.toLegacyResponse(): LegacyBlock =
+ when (this) {
+ is AttoOpenBlock -> {
+ LegacyBlock.Open(
+ network = network,
+ version = version,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ address = address,
+ height = height,
+ balance = balance,
+ timestamp = timestamp,
+ sendHashAlgorithm = sendHashAlgorithm,
+ sendHash = sendHash,
+ representativeAlgorithm = representativeAddress.algorithm,
+ representativePublicKey = representativeAddress.publicKey,
+ representativeAddress = representativeAddress,
+ )
+ }
+
+ is AttoReceiveBlock -> {
+ LegacyBlock.Receive(
+ network = network,
+ version = version,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ address = address,
+ height = height,
+ balance = balance,
+ timestamp = timestamp,
+ previous = previous,
+ sendHashAlgorithm = sendHashAlgorithm,
+ sendHash = sendHash,
+ )
+ }
+
+ is AttoSendBlock -> {
+ LegacyBlock.Send(
+ network = network,
+ version = version,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ address = address,
+ height = height,
+ balance = balance,
+ timestamp = timestamp,
+ previous = previous,
+ receiverAlgorithm = receiverAddress.algorithm,
+ receiverPublicKey = receiverAddress.publicKey,
+ receiverAddress = receiverAddress,
+ amount = amount,
+ )
+ }
+
+ is AttoChangeBlock -> {
+ LegacyBlock.Change(
+ network = network,
+ version = version,
+ algorithm = address.algorithm,
+ publicKey = address.publicKey,
+ address = address,
+ height = height,
+ balance = balance,
+ timestamp = timestamp,
+ previous = previous,
+ representativeAlgorithm = representativeAddress.algorithm,
+ representativePublicKey = representativeAddress.publicKey,
+ representativeAddress = representativeAddress,
+ )
+ }
+ }
diff --git a/src/main/kotlin/cash/atto/node/transaction/Transaction.kt b/src/main/kotlin/cash/atto/node/transaction/Transaction.kt
index e0fbf74a..e5215b19 100644
--- a/src/main/kotlin/cash/atto/node/transaction/Transaction.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/Transaction.kt
@@ -36,9 +36,9 @@ data class Transaction(
val hash = block.hash
@Transient
- val algorithm = block.algorithm
+ val algorithm = block.address.algorithm
- val publicKey = block.publicKey
+ val publicKey = block.address.publicKey
val height = block.height
val serialized: Buffer
@@ -55,7 +55,7 @@ data class Transaction(
work = work,
)
- fun toPublicKeyHeight(): PublicKeyHeight = PublicKeyHeight(this.block.publicKey, this.block.height)
+ fun toPublicKeyHeight(): PublicKeyHeight = PublicKeyHeight(this.block.address.publicKey, this.block.height)
override fun equals(other: Any?): Boolean {
if (this === other) return true
diff --git a/src/main/kotlin/cash/atto/node/transaction/TransactionBulkRepositoryImpl.kt b/src/main/kotlin/cash/atto/node/transaction/TransactionBulkRepositoryImpl.kt
index ec6ca991..5e540bed 100644
--- a/src/main/kotlin/cash/atto/node/transaction/TransactionBulkRepositoryImpl.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/TransactionBulkRepositoryImpl.kt
@@ -34,8 +34,8 @@ class TransactionBulkRepositoryImpl(
statement
.bind(bindIndex++, block.hash.value)
- .bind(bindIndex++, block.algorithm.name)
- .bind(bindIndex++, block.publicKey.value)
+ .bind(bindIndex++, block.address.algorithm.name)
+ .bind(bindIndex++, block.address.publicKey.value)
.bind(bindIndex++, block.height.value.toBigInteger())
.bind(bindIndex++, block.type.name)
.bind(bindIndex++, block.timestamp.toJavaInstant())
diff --git a/src/main/kotlin/cash/atto/node/transaction/TransactionConfiguration.kt b/src/main/kotlin/cash/atto/node/transaction/TransactionConfiguration.kt
index b3d4edfe..7b23fd0f 100644
--- a/src/main/kotlin/cash/atto/node/transaction/TransactionConfiguration.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/TransactionConfiguration.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoInstant
@@ -96,11 +97,11 @@ class TransactionConfiguration(
network = block.network,
hash = block.sendHash,
version = block.version,
- algorithm = block.algorithm,
- publicKey = block.publicKey,
+ algorithm = block.address.algorithm,
+ publicKey = block.address.publicKey,
timestamp = block.timestamp.toJavaInstant(),
- receiverAlgorithm = block.algorithm,
- receiverPublicKey = block.publicKey,
+ receiverAlgorithm = block.address.algorithm,
+ receiverPublicKey = block.address.publicKey,
amount = block.balance,
)
@@ -111,7 +112,7 @@ class TransactionConfiguration(
val network = thisNode.network
val hash = genesisTransaction.hash
logger.info { "Initialized $network database with genesis transaction hash $hash" }
- } else if (transactionRepository.findFirstByPublicKey(genesisTransaction.block.publicKey) == null) {
+ } else if (transactionRepository.findFirstByPublicKey(genesisTransaction.block.address.publicKey) == null) {
throw IllegalStateException("Database initialized but doesn't contains current genesis account")
}
}
@@ -124,14 +125,12 @@ class TransactionConfiguration(
AttoOpenBlock(
version = 0U.toAttoVersion(),
network = thisNode.network,
- algorithm = thisNode.algorithm,
- publicKey = signer.publicKey,
+ address = AttoAddress(thisNode.algorithm, signer.publicKey),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
sendHashAlgorithm = thisNode.algorithm,
sendHash = AttoHash(ByteArray(32)),
- representativeAlgorithm = thisNode.algorithm,
- representativePublicKey = signer.publicKey,
+ representativeAddress = AttoAddress(thisNode.algorithm, signer.publicKey),
)
val transaction =
diff --git a/src/main/kotlin/cash/atto/node/transaction/TransactionController.kt b/src/main/kotlin/cash/atto/node/transaction/TransactionController.kt
index 93a58107..e57c6afb 100644
--- a/src/main/kotlin/cash/atto/node/transaction/TransactionController.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/TransactionController.kt
@@ -1,34 +1,19 @@
package cash.atto.node.transaction
import cash.atto.commons.AttoAddress
-import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoHeight
import cash.atto.commons.AttoPublicKey
import cash.atto.commons.AttoTransaction
-import cash.atto.commons.node.AccountHeightSearch
import cash.atto.commons.node.HeightSearch
-import cash.atto.commons.spring.sortByHeight
-import cash.atto.commons.toBigInteger
-import cash.atto.node.account.AccountUpdated
-import io.github.oshai.kotlinlogging.KotlinLogging
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.emitAll
-import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.flow.merge
-import kotlinx.coroutines.flow.onCompletion
-import kotlinx.coroutines.flow.onStart
-import kotlinx.coroutines.flow.onSubscription
-import kotlinx.coroutines.flow.take
-import org.springframework.context.event.EventListener
-import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
@@ -38,7 +23,6 @@ import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
-import org.springframework.web.server.ResponseStatusException
@RestController
@RequestMapping
@@ -50,18 +34,10 @@ import org.springframework.web.server.ResponseStatusException
"See [payment failure recovery](https://atto.cash/docs/whitepaper/technical#payment-failure-recovery).",
)
class TransactionController(
- val repository: TransactionRepository,
+ private val queries: TransactionQueries,
) {
- private val logger = KotlinLogging.logger {}
-
- private val transactionFlow = MutableSharedFlow()
-
- @EventListener
- suspend fun process(accountUpdated: AccountUpdated) {
- transactionFlow.emit(accountUpdated.transaction.toAttoTransaction())
- }
-
@Operation(
+ operationId = "streamAllTransactions",
summary = "Stream all latest transactions",
responses = [
ApiResponse(
@@ -74,35 +50,15 @@ class TransactionController(
),
],
)
- @GetMapping("/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
- suspend fun stream(): Flow =
- transactionFlow
- .onStart { logger.trace { "Started streaming latest transactions" } }
- .onCompletion { logger.trace { "Stopped streaming latest transactions" } }
+ @GetMapping("/v2/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(): Flow = queries.stream()
- @GetMapping("/transactions/{hash}")
- @Operation(
- summary = "Get transaction",
- responses = [
- ApiResponse(
- responseCode = "200",
- content = [
- Content(
- schema = Schema(implementation = AttoTransaction::class),
- ),
- ],
- ),
- ],
- )
suspend fun get(
@PathVariable hash: AttoHash,
- ): ResponseEntity {
- val transaction = repository.findById(hash)
- return ResponseEntity.ofNullable(transaction?.toAttoTransaction())
- }
+ ): ResponseEntity = ResponseEntity.ofNullable(queries.get(hash))
- @GetMapping("/transactions/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamTransactionByHash",
summary = "Stream a single transaction",
description =
"Allows clients to track the confirmation of a transaction in real-time by streaming a single transaction by hash. " +
@@ -118,19 +74,13 @@ class TransactionController(
),
],
)
+ @GetMapping("/v2/transactions/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
suspend fun stream(
@PathVariable hash: AttoHash,
- ): Flow =
- transactionFlow
- .onSubscription {
- repository.findById(hash)?.let { emit(it.toAttoTransaction()) }
- }.filter { it.hash == hash }
- .onStart { logger.trace { "Started streaming $hash transaction" } }
- .onCompletion { logger.trace { "Stopped streaming $hash transaction" } }
- .take(1)
+ ): Flow = queries.stream(hash)
- @PostMapping("/accounts/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
@Operation(
+ operationId = "streamTransactionsByHeightRanges",
summary = "Stream transactions by account and height range",
responses = [
ApiResponse(
@@ -143,74 +93,120 @@ class TransactionController(
),
],
)
+ @PostMapping("/v2/accounts/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
suspend fun streamMultiple(
@RequestBody search: HeightSearch,
- ): Flow {
- val accountRanges = search.search
+ ): Flow = queries.streamMultiple(search)
- if (accountRanges.any { it.fromHeight.value == 0UL }) {
- throw ResponseStatusException(HttpStatus.BAD_REQUEST, "fromHeight can't be zero")
- }
- if (accountRanges.any { it.fromHeight > it.toHeight }) {
- throw ResponseStatusException(HttpStatus.BAD_REQUEST, "toHeight must be greater or equal to fromHeight")
- }
+ @Operation(
+ operationId = "streamTransactionsByAddress",
+ summary = "Stream transactions by address and height range",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [Content(schema = Schema(implementation = AttoTransaction::class))],
+ ),
+ ],
+ )
+ @GetMapping("/v2/accounts/{address}/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun stream(
+ @PathVariable address: AttoAddress,
+ @RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
+ @RequestParam(required = false) toHeight: AttoHeight = AttoHeight.MAX,
+ ): Flow = stream(address.publicKey, fromHeight, toHeight)
- val accountFlows =
- accountRanges.map { range ->
- val publicKey = range.address.publicKey
- val fromHeight = range.fromHeight
- val toHeight = range.toHeight
- val expectedCount =
- (range.toHeight - range.fromHeight + 1UL).let {
- if (it.value > Int.MAX_VALUE.toUInt()) Int.MAX_VALUE else it.value.toInt()
- }
+ suspend fun stream(
+ @PathVariable publicKey: AttoPublicKey,
+ @RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
+ @RequestParam(required = false) toHeight: AttoHeight = AttoHeight.MAX,
+ ): Flow = queries.stream(publicKey, fromHeight, toHeight)
- transactionFlow
- .onSubscription {
- emitAll(
- repository
- .findAsc(publicKey, fromHeight.value.toBigInteger(), toHeight.value.toBigInteger())
- .map { it.toAttoTransaction() },
- )
- }.filter { it.block.publicKey == publicKey && it.height in fromHeight..toHeight }
- .sortByHeight(fromHeight)
- .take(expectedCount)
- }
+ @Hidden
+ @Operation(
+ operationId = "streamAllLegacyTransactions",
+ summary = "Stream all latest transactions",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyTransactionResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @GetMapping("/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(): Flow = stream().map { it.toLegacyResponse() }
- return merge(*accountFlows.toTypedArray())
- .onStart {
- logger.trace { "Started streaming transactions for ${accountRanges.size} accounts" }
- }.onCompletion {
- logger.trace { "Stopped streaming transactions for ${accountRanges.size} accounts" }
- }
- }
+ @Operation(
+ operationId = "getTransactionByHash",
+ summary = "Get transaction",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyTransactionResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @GetMapping("/transactions/{hash}")
+ suspend fun legacyGet(
+ @PathVariable hash: AttoHash,
+ ): ResponseEntity = get(hash).let { ResponseEntity(it.body?.toLegacyResponse(), it.headers, it.statusCode) }
- @GetMapping("/accounts/{publicKey}/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ @Hidden
@Operation(
- summary = "Stream transactions by height",
+ operationId = "streamLegacyTransactionByHash",
+ summary = "Stream a single transaction",
+ description =
+ "Allows clients to track the confirmation of a transaction in real-time by streaming a single transaction by hash. " +
+ "Useful when the transaction hash is shared ahead of time, like in payment protocols.",
responses = [
ApiResponse(
responseCode = "200",
content = [
Content(
- schema = Schema(implementation = AttoTransaction::class),
+ schema = Schema(implementation = LegacyTransactionResponse::class),
),
],
),
],
)
- suspend fun stream(
+ @GetMapping("/transactions/{hash}/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
+ @PathVariable hash: AttoHash,
+ ): Flow = stream(hash).map { it.toLegacyResponse() }
+
+ @Hidden
+ @Operation(
+ operationId = "streamLegacyTransactionsByHeightRanges",
+ summary = "Stream transactions by account and height range",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyTransactionResponse::class),
+ ),
+ ],
+ ),
+ ],
+ )
+ @PostMapping("/accounts/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStreamMultiple(
+ @RequestBody search: HeightSearch,
+ ): Flow = streamMultiple(search).map { it.toLegacyResponse() }
+
+ @Hidden
+ @Operation(operationId = "streamLegacyTransactionsByPublicKey")
+ @GetMapping("/accounts/{publicKey}/transactions/stream", produces = [MediaType.APPLICATION_NDJSON_VALUE])
+ suspend fun legacyStream(
@PathVariable publicKey: AttoPublicKey,
@RequestParam(defaultValue = "1", required = false) fromHeight: AttoHeight,
@RequestParam(required = false) toHeight: AttoHeight = AttoHeight.MAX,
- ): Flow {
- val transactionSearch =
- AccountHeightSearch(
- AttoAddress(AttoAlgorithm.V1, publicKey),
- fromHeight,
- toHeight,
- )
- val search = HeightSearch(listOf(transactionSearch))
- return streamMultiple(search)
- }
+ ): Flow = stream(publicKey, fromHeight, toHeight).map { it.toLegacyResponse() }
}
diff --git a/src/main/kotlin/cash/atto/node/transaction/TransactionPublicationController.kt b/src/main/kotlin/cash/atto/node/transaction/TransactionPublicationController.kt
index ea052fb8..c26f382c 100644
--- a/src/main/kotlin/cash/atto/node/transaction/TransactionPublicationController.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/TransactionPublicationController.kt
@@ -13,6 +13,7 @@ import cash.atto.node.transaction.PendingTransactionRegistry.Stream
import cash.atto.protocol.AttoNode
import cash.atto.protocol.AttoTransactionPush
import io.github.oshai.kotlinlogging.KotlinLogging
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.media.Content
@@ -55,8 +56,6 @@ class TransactionPublicationController(
) {
private val logger = KotlinLogging.logger {}
- private val useXForwardedForKey = "X-FORWARDED-FOR"
-
private val pendingTransactions = PendingTransactionRegistry()
@EventListener
@@ -154,46 +153,6 @@ class TransactionPublicationController(
)
}
- @PostMapping("/transactions", consumes = [MediaType.APPLICATION_JSON_VALUE])
- @Operation(
- summary = "Publish a transaction",
- description =
- "Validates and publishes the signed transaction, then waits for local confirmation and returns the confirmed transaction. " +
- "The confirmation wait has a 40-second timeout. After a timeout or lost response, inspect the original hash and " +
- "account history before creating another payment; confirmation may already have happened. " +
- "A confirmed Send creates a receivable; a separate Open or Receive adds it to the recipient's spendable balance.",
- responses = [
- ApiResponse(
- responseCode = "200",
- description = "The confirmed transaction, including an already confirmed result when recognized by the node.",
- content = [
- Content(
- schema = Schema(implementation = AttoTransaction::class),
- ),
- ],
- ),
- ApiResponse(
- responseCode = "400",
- description = "Invalid transaction, wrong network, invalid proxy-header configuration, or transaction rejection.",
- content = [Content()],
- ),
- ApiResponse(
- responseCode = "409",
- description = "The local election rejected this publication attempt and the hash was not found in local storage.",
- content = [Content()],
- ),
- ApiResponse(
- responseCode = "429",
- description = "The local transaction queue dropped the transaction. Check its hash before retrying the payment.",
- content = [Content()],
- ),
- ApiResponse(
- responseCode = "503",
- description = "The local election expired. This does not prove that the transaction failed on every node.",
- content = [Content()],
- ),
- ],
- )
suspend fun publish(
@RequestBody transaction: AttoTransaction,
request: ServerHttpRequest,
@@ -249,7 +208,7 @@ class TransactionPublicationController(
transaction: AttoTransaction,
request: ServerHttpRequest,
): InetSocketAddress {
- val ips = request.headers[useXForwardedForKey] ?: listOf()
+ val ips = request.headers["X-FORWARDED-FOR"] ?: emptyList()
val remoteAddress = request.remoteAddress!!
return if (!applicationProperties.useXForwardedFor) {
@@ -280,15 +239,16 @@ class TransactionPublicationController(
}
@PostMapping(
- "/transactions/stream",
+ "/v2/transactions",
consumes = [MediaType.APPLICATION_JSON_VALUE],
produces = [MediaType.APPLICATION_NDJSON_VALUE],
)
@Operation(
- summary = "Publish a transaction and stream its confirmation",
+ operationId = "publishTransactionAndWaitForConfirmation",
+ summary = "Publish a transaction and wait for confirmation",
description =
- "Uses the same publication and local-confirmation operation as POST /transactions, " +
- "emitting one confirmed transaction as NDJSON. " +
+ "Validates and publishes the signed transaction, waits for local confirmation, " +
+ "then returns the confirmed transaction as NDJSON. " +
"The confirmation wait has a 40-second timeout. Inspect the emitted transaction, not only the initial HTTP status. " +
"Errors after response commitment can terminate the stream; do not assume every timeout returns HTTP 504. " +
"After an interrupted stream, inspect the original hash and account history before creating another payment.",
@@ -349,4 +309,109 @@ class TransactionPublicationController(
}
}.first()
}
+
+ @Operation(
+ operationId = "publishLegacyTransactionAndWaitForConfirmation",
+ summary = "Publish a transaction and wait for confirmation",
+ description =
+ "Validates and publishes the signed transaction, then waits for local confirmation and returns the confirmed transaction. " +
+ "The confirmation wait has a 40-second timeout. After a timeout or lost response, inspect the original hash and " +
+ "account history before creating another payment; confirmation may already have happened. " +
+ "A confirmed Send creates a receivable; a separate Open or Receive adds it to the recipient's spendable balance.",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ description = "The confirmed transaction, including an already confirmed result when recognized by the node.",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyTransactionResponse::class),
+ ),
+ ],
+ ),
+ ApiResponse(
+ responseCode = "400",
+ description = "Invalid transaction, wrong network, invalid proxy-header configuration, or transaction rejection.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "409",
+ description = "The local election rejected this publication attempt and the hash was not found in local storage.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "429",
+ description = "The local transaction queue dropped the transaction. Check its hash before retrying the payment.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "503",
+ description = "The local election expired. This does not prove that the transaction failed on every node.",
+ content = [Content()],
+ ),
+ ],
+ )
+ @PostMapping("/transactions", consumes = [MediaType.APPLICATION_JSON_VALUE])
+ suspend fun legacyPublish(
+ @RequestBody transaction: LegacyTransactionRequest,
+ request: ServerHttpRequest,
+ @Parameter(
+ description =
+ "When true, reuse a stored confirmation or an existing pending publication for the same transaction hash. " +
+ "This does not deduplicate payment attempts with different transaction hashes.",
+ )
+ @RequestParam(defaultValue = "false", required = false) deduplicate: Boolean = false,
+ ): LegacyTransactionResponse = publish(transaction.transaction, request, deduplicate).toLegacyResponse()
+
+ @Hidden
+ @Operation(
+ operationId = "publishLegacyTransactionAndWaitForConfirmationAsNdjson",
+ summary = "Publish a transaction and wait for confirmation",
+ description =
+ "Validates and publishes the signed transaction, waits for local confirmation, " +
+ "then returns the confirmed transaction as NDJSON. " +
+ "The confirmation wait has a 40-second timeout. Inspect the emitted transaction, not only the initial HTTP status. " +
+ "Errors after response commitment can terminate the stream; do not assume every timeout returns HTTP 504. " +
+ "After an interrupted stream, inspect the original hash and account history before creating another payment.",
+ responses = [
+ ApiResponse(
+ responseCode = "200",
+ description = "One confirmed transaction emitted as NDJSON.",
+ content = [
+ Content(
+ schema = Schema(implementation = LegacyTransactionResponse::class),
+ ),
+ ],
+ ),
+ ApiResponse(
+ responseCode = "400",
+ description = "Invalid or rejected transaction, or invalid proxy-header configuration, before response commitment.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "409",
+ description = "The local election rejected this publication attempt before response commitment.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "429",
+ description = "The local transaction queue dropped the transaction before response commitment.",
+ content = [Content()],
+ ),
+ ApiResponse(
+ responseCode = "503",
+ description = "The local election expired before response commitment.",
+ content = [Content()],
+ ),
+ ],
+ )
+ @PostMapping(
+ "/transactions/stream",
+ consumes = [MediaType.APPLICATION_JSON_VALUE],
+ produces = [MediaType.APPLICATION_NDJSON_VALUE],
+ )
+ suspend fun legacyPublishAndStream(
+ @RequestBody transaction: LegacyTransactionRequest,
+ request: ServerHttpRequest,
+ @RequestParam(defaultValue = "false", required = false) deduplicate: Boolean = false,
+ ): Flow = publishAndStream(transaction.transaction, request, deduplicate).map { it.toLegacyResponse() }
}
diff --git a/src/main/kotlin/cash/atto/node/transaction/TransactionQueries.kt b/src/main/kotlin/cash/atto/node/transaction/TransactionQueries.kt
new file mode 100644
index 00000000..f3e712e9
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/transaction/TransactionQueries.kt
@@ -0,0 +1,116 @@
+package cash.atto.node.transaction
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoTransaction
+import cash.atto.commons.node.AccountHeightSearch
+import cash.atto.commons.node.HeightSearch
+import cash.atto.commons.spring.sortByHeight
+import cash.atto.commons.toBigInteger
+import cash.atto.node.account.AccountUpdated
+import cash.atto.node.account.validateRanges
+import io.github.oshai.kotlinlogging.KotlinLogging
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.filter
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.flow.onCompletion
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.flow.onSubscription
+import kotlinx.coroutines.flow.take
+import org.springframework.context.event.EventListener
+import org.springframework.stereotype.Component
+
+@Component
+class TransactionQueries(
+ private val repository: TransactionRepository,
+) {
+ private val logger = KotlinLogging.logger {}
+
+ private val transactionFlow = MutableSharedFlow()
+
+ @EventListener
+ suspend fun process(accountUpdated: AccountUpdated) {
+ transactionFlow.emit(accountUpdated.transaction.toAttoTransaction())
+ }
+
+ suspend fun stream(): Flow =
+ transactionFlow
+ .onStart { logger.trace { "Started streaming latest transactions" } }
+ .onCompletion { logger.trace { "Stopped streaming latest transactions" } }
+
+ suspend fun get(hash: AttoHash): AttoTransaction? {
+ val transaction = repository.findById(hash)
+ return transaction?.toAttoTransaction()
+ }
+
+ suspend fun stream(hash: AttoHash): Flow =
+ transactionFlow
+ .onSubscription {
+ repository.findById(hash)?.let { emit(it.toAttoTransaction()) }
+ }.filter { it.hash == hash }
+ .onStart { logger.trace { "Started streaming $hash transaction" } }
+ .onCompletion { logger.trace { "Stopped streaming $hash transaction" } }
+ .take(1)
+
+ suspend fun streamMultiple(search: HeightSearch): Flow {
+ val accountRanges = search.search
+
+ search.validateRanges()
+
+ val accountFlows =
+ accountRanges.map { range ->
+ val publicKey = range.address.publicKey
+ val fromHeight = range.fromHeight
+ val toHeight = range.toHeight
+ val expectedCount =
+ (range.toHeight - range.fromHeight + 1UL).let {
+ if (it.value > Int.MAX_VALUE.toUInt()) Int.MAX_VALUE else it.value.toInt()
+ }
+
+ transactionFlow
+ .onSubscription {
+ emitAll(
+ repository
+ .findAsc(publicKey, fromHeight.value.toBigInteger(), toHeight.value.toBigInteger())
+ .map { it.toAttoTransaction() },
+ )
+ }.filter { it.block.address.publicKey == publicKey && it.height in fromHeight..toHeight }
+ .sortByHeight(fromHeight)
+ .take(expectedCount)
+ }
+
+ return merge(*accountFlows.toTypedArray())
+ .onStart {
+ logger.trace { "Started streaming transactions for ${accountRanges.size} accounts" }
+ }.onCompletion {
+ logger.trace { "Stopped streaming transactions for ${accountRanges.size} accounts" }
+ }
+ }
+
+ suspend fun stream(
+ address: AttoAddress,
+ fromHeight: AttoHeight,
+ toHeight: AttoHeight = AttoHeight.MAX,
+ ): Flow = stream(address.publicKey, fromHeight, toHeight)
+
+ suspend fun stream(
+ publicKey: AttoPublicKey,
+ fromHeight: AttoHeight,
+ toHeight: AttoHeight = AttoHeight.MAX,
+ ): Flow {
+ val transactionSearch =
+ AccountHeightSearch(
+ AttoAddress(AttoAlgorithm.V1, publicKey),
+ fromHeight,
+ toHeight,
+ )
+ val search = HeightSearch(listOf(transactionSearch))
+ return streamMultiple(search)
+ }
+}
diff --git a/src/main/kotlin/cash/atto/node/transaction/validation/TransactionValidationManager.kt b/src/main/kotlin/cash/atto/node/transaction/validation/TransactionValidationManager.kt
index 66bf6419..1f9cf5e0 100644
--- a/src/main/kotlin/cash/atto/node/transaction/validation/TransactionValidationManager.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/validation/TransactionValidationManager.kt
@@ -34,7 +34,7 @@ class TransactionValidationManager(
val account: Account
val violation: TransactionViolation?
try {
- account = accountRepository.getByAlgorithmAndPublicKey(block.algorithm, block.publicKey, block.network)
+ account = accountRepository.getByAlgorithmAndPublicKey(block.address.algorithm, block.address.publicKey, block.network)
violation = validate(account, transaction)
} catch (exception: CancellationException) {
throw exception
diff --git a/src/main/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidator.kt b/src/main/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidator.kt
index 7f83200c..28cdf908 100644
--- a/src/main/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidator.kt
+++ b/src/main/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidator.kt
@@ -20,7 +20,7 @@ class ChangeValidator : TransactionValidator {
): TransactionViolation? {
val block = transaction.block as AttoChangeBlock
- if (account.representativePublicKey == block.representativePublicKey) {
+ if (account.representativePublicKey == block.representativeAddress.publicKey) {
return TransactionViolation(
TransactionRejectionReason.INVALID_REPRESENTATIVE,
"The account ${account.lastTransactionHash} already has the " +
diff --git a/src/main/kotlin/cash/atto/node/vote/Vote.kt b/src/main/kotlin/cash/atto/node/vote/Vote.kt
index 8bdd77e2..cd29be73 100644
--- a/src/main/kotlin/cash/atto/node/vote/Vote.kt
+++ b/src/main/kotlin/cash/atto/node/vote/Vote.kt
@@ -1,5 +1,6 @@
package cash.atto.node.vote
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -45,8 +46,8 @@ data class Vote(
return Vote(
hash = attoSignedVote.hash,
version = attoVote.version,
- algorithm = attoVote.algorithm,
- publicKey = attoVote.publicKey,
+ algorithm = attoVote.address.algorithm,
+ publicKey = attoVote.address.publicKey,
blockAlgorithm = attoVote.blockAlgorithm,
blockHash = attoVote.blockHash,
timestamp = attoVote.timestamp.toJavaInstant(),
@@ -68,8 +69,7 @@ data class Vote(
val vote =
AttoVote(
version = version,
- algorithm = algorithm,
- publicKey = publicKey,
+ address = AttoAddress(algorithm, publicKey),
blockAlgorithm = blockAlgorithm,
blockHash = blockHash,
timestamp = timestamp.toAtto(),
diff --git a/src/main/kotlin/cash/atto/node/vote/VoteNetworkProvider.kt b/src/main/kotlin/cash/atto/node/vote/VoteNetworkProvider.kt
index 7303fa31..7811224d 100644
--- a/src/main/kotlin/cash/atto/node/vote/VoteNetworkProvider.kt
+++ b/src/main/kotlin/cash/atto/node/vote/VoteNetworkProvider.kt
@@ -1,5 +1,6 @@
package cash.atto.node.vote
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoSignedVote
@@ -68,8 +69,7 @@ class VoteNetworkProvider(
val attoVote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = thisNode.algorithm,
- publicKey = thisNode.publicKey,
+ address = AttoAddress(thisNode.algorithm, thisNode.publicKey),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = request.blockHash,
timestamp = AttoVote.finalTimestamp,
diff --git a/src/main/kotlin/cash/atto/node/vote/convertion/VoteConverter.kt b/src/main/kotlin/cash/atto/node/vote/convertion/VoteConverter.kt
index 7e3ff201..5765c4c0 100644
--- a/src/main/kotlin/cash/atto/node/vote/convertion/VoteConverter.kt
+++ b/src/main/kotlin/cash/atto/node/vote/convertion/VoteConverter.kt
@@ -22,7 +22,7 @@ class VoteConverter(
}
fun convert(attoVote: AttoSignedVote): Vote {
- val weight = weightService.get(attoVote.vote.publicKey)
+ val weight = weightService.get(attoVote.vote.address.publicKey)
return Vote.from(weight, attoVote)
}
}
diff --git a/src/main/kotlin/cash/atto/node/vote/keeping/VoteKeeper.kt b/src/main/kotlin/cash/atto/node/vote/keeping/VoteKeeper.kt
index 0b2e6638..e82cb520 100644
--- a/src/main/kotlin/cash/atto/node/vote/keeping/VoteKeeper.kt
+++ b/src/main/kotlin/cash/atto/node/vote/keeping/VoteKeeper.kt
@@ -1,5 +1,6 @@
package cash.atto.node.vote.keeping
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoHash
import cash.atto.commons.AttoSignedVote
@@ -54,13 +55,13 @@ class VoteKeeper(
suspend fun process(message: InboundNetworkMessage) {
val response = message.payload
val signedVote = response.vote
- val missingVote = MissingVote(signedVote.vote.blockHash, signedVote.vote.publicKey)
+ val missingVote = MissingVote(signedVote.vote.blockHash, signedVote.vote.address.publicKey)
if (missingVoteMap.remove(missingVote) == null) {
return
}
- voteService.enqueue(Vote.from(voteWeighter.get(signedVote.vote.publicKey), signedVote))
+ voteService.enqueue(Vote.from(voteWeighter.get(signedVote.vote.address.publicKey), signedVote))
}
@Scheduled(fixedRate = 10, timeUnit = TimeUnit.MINUTES)
@@ -103,8 +104,7 @@ class VoteKeeper(
val attoVote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = thisNode.algorithm,
- publicKey = thisNode.publicKey,
+ address = AttoAddress(thisNode.algorithm, thisNode.publicKey),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = blockHash,
timestamp = AttoVote.finalTimestamp,
@@ -115,7 +115,7 @@ class VoteKeeper(
signature = signer.sign(attoVote),
)
- return Vote.from(voteWeighter.get(signedVote.vote.publicKey), signedVote)
+ return Vote.from(voteWeighter.get(signedVote.vote.address.publicKey), signedVote)
}
override fun clear() {
diff --git a/src/main/kotlin/cash/atto/node/vote/weight/LegacyVoterWeightResponse.kt b/src/main/kotlin/cash/atto/node/vote/weight/LegacyVoterWeightResponse.kt
new file mode 100644
index 00000000..cdb4ddbe
--- /dev/null
+++ b/src/main/kotlin/cash/atto/node/vote/weight/LegacyVoterWeightResponse.kt
@@ -0,0 +1,20 @@
+package cash.atto.node.vote.weight
+
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoInstant
+import cash.atto.node.LegacyAmountSerializer
+import cash.atto.node.LegacyInstantSerializer
+import io.swagger.v3.oas.annotations.media.Schema
+import kotlinx.serialization.Serializable
+
+@Serializable
+data class LegacyVoterWeightResponse(
+ val address: AttoAddress,
+ @get:Schema(type = "integer", format = "uint64", implementation = java.math.BigInteger::class)
+ @Serializable(with = LegacyAmountSerializer::class)
+ val weight: AttoAmount,
+ @get:Schema(type = "integer", format = "int64", implementation = Long::class)
+ @Serializable(with = LegacyInstantSerializer::class)
+ val lastVotedAt: AttoInstant,
+)
diff --git a/src/main/kotlin/cash/atto/node/vote/weight/VoteWeightController.kt b/src/main/kotlin/cash/atto/node/vote/weight/VoteWeightController.kt
index f18cc00f..058ee44d 100644
--- a/src/main/kotlin/cash/atto/node/vote/weight/VoteWeightController.kt
+++ b/src/main/kotlin/cash/atto/node/vote/weight/VoteWeightController.kt
@@ -1,7 +1,6 @@
package cash.atto.node.vote.weight
import cash.atto.commons.AttoAddress
-import cash.atto.commons.AttoVoterWeight
import cash.atto.commons.toAtto
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Content
@@ -22,6 +21,7 @@ class VoteWeightController(
) {
@GetMapping("/{address}")
@Operation(
+ operationId = "getVoterWeightByAddress",
summary = "Get voter weight",
responses = [
ApiResponse(
@@ -36,10 +36,10 @@ class VoteWeightController(
)
fun get(
@PathVariable address: AttoAddress,
- ): ResponseEntity {
+ ): ResponseEntity {
val weight = voteWeighter.get(address.publicKey)
val lastVotedAt = voteWeighter.getLatestVoteTimestamp(address.publicKey).toAtto()
- val voterWeight = AttoVoterWeight(address, weight, lastVotedAt)
+ val voterWeight = LegacyVoterWeightResponse(address, weight, lastVotedAt)
return ResponseEntity.ok(voterWeight)
}
}
diff --git a/src/main/kotlin/cash/atto/node/vote/weight/VoteWeighter.kt b/src/main/kotlin/cash/atto/node/vote/weight/VoteWeighter.kt
index 14bb8685..2d034930 100644
--- a/src/main/kotlin/cash/atto/node/vote/weight/VoteWeighter.kt
+++ b/src/main/kotlin/cash/atto/node/vote/weight/VoteWeighter.kt
@@ -84,7 +84,7 @@ class VoteWeighter(
when (block) {
is AttoOpenBlock -> {
- add(block.representativePublicKey, block.balance, block.balance)
+ add(block.representativeAddress.publicKey, block.balance, block.balance)
}
is AttoReceiveBlock -> {
@@ -99,7 +99,7 @@ class VoteWeighter(
is AttoChangeBlock -> {
subtract(previousAccount.representativePublicKey, block.balance)
- add(block.representativePublicKey, block.balance, block.balance)
+ add(block.representativeAddress.publicKey, block.balance, block.balance)
}
}
diff --git a/src/test/kotlin/cash/atto/node/HttpApiTest.kt b/src/test/kotlin/cash/atto/node/HttpApiTest.kt
new file mode 100644
index 00000000..8e5f0dbb
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/HttpApiTest.kt
@@ -0,0 +1,768 @@
+package cash.atto.node
+
+import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoBlockType
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoReceivable
+import cash.atto.commons.AttoSendBlock
+import cash.atto.commons.AttoSignature
+import cash.atto.commons.AttoTransaction
+import cash.atto.commons.AttoWork
+import cash.atto.commons.node.AccountSearch
+import cash.atto.commons.spring.conversion.AttoConversionsAutoConfiguration
+import cash.atto.commons.spring.schema.AttoSpringDocOpenApiAutoConfiguration
+import cash.atto.commons.toAttoVersion
+import cash.atto.node.account.AccountController
+import cash.atto.node.account.AccountQueries
+import cash.atto.node.account.LegacyHttpFixtures
+import cash.atto.node.account.entry.AccountEntryController
+import cash.atto.node.account.entry.AccountEntryQueries
+import cash.atto.node.receivable.ReceivableController
+import cash.atto.node.receivable.ReceivableQueries
+import cash.atto.node.transaction.TransactionController
+import cash.atto.node.transaction.TransactionPublicationController
+import cash.atto.node.transaction.TransactionQueries
+import io.mockk.coEvery
+import io.mockk.coVerify
+import io.mockk.every
+import io.mockk.mockk
+import io.mockk.spyk
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.encodeToJsonElement
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.springdoc.core.configuration.SpringDocConfiguration
+import org.springdoc.core.configuration.SpringDocKotlinxConfiguration
+import org.springdoc.core.properties.SpringDocConfigProperties
+import org.springdoc.webflux.core.configuration.SpringDocWebFluxConfiguration
+import org.springframework.boot.reactor.netty.NettyReactiveWebServerFactory
+import org.springframework.boot.web.context.reactive.AnnotationConfigReactiveWebApplicationContext
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.http.ResponseEntity
+import org.springframework.http.codec.ServerCodecConfigurer
+import org.springframework.web.reactive.config.EnableWebFlux
+import org.springframework.web.reactive.config.WebFluxConfigurer
+import org.springframework.web.server.adapter.WebHttpHandlerBuilder
+import java.net.URI
+import java.net.URLEncoder
+import java.net.http.HttpClient
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+import java.nio.charset.StandardCharsets
+import java.nio.file.Files
+import java.nio.file.Path
+import java.time.Duration
+import java.util.concurrent.atomic.AtomicInteger
+
+class HttpApiTest {
+ @Test
+ fun `encoded address routes delegate the public key and preserve query defaults and legacy routes`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val publicKey = AttoPublicKey(ByteArray(32) { 1 })
+ val address = AttoAddress(AttoAlgorithm.V1, publicKey)
+ val encodedAddress = URLEncoder.encode(address.toString(), StandardCharsets.UTF_8)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val scalar = get(client, "$baseUrl/v2/accounts/$encodedAddress")
+ val account = get(client, "$baseUrl/v2/accounts/$encodedAddress/stream")
+ val receivables = get(client, "$baseUrl/v2/accounts/$encodedAddress/receivables/stream?minAmount=7")
+ val entries = get(client, "$baseUrl/v2/accounts/$encodedAddress/entries/stream?fromHeight=2&toHeight=5")
+ val transactions = get(client, "$baseUrl/v2/accounts/$encodedAddress/transactions/stream")
+ val defaultReceivables = get(client, "$baseUrl/v2/accounts/$encodedAddress/receivables/stream")
+ val defaultEntries = get(client, "$baseUrl/v2/accounts/$encodedAddress/entries/stream")
+ val legacy = get(client, "$baseUrl/accounts/$publicKey")
+ val legacyStream = get(client, "$baseUrl/accounts/$publicKey/stream")
+
+ // Then
+ assertEquals(404, scalar.statusCode())
+ assertEquals(404, legacy.statusCode())
+ for (response in listOf(account, receivables, entries, transactions, defaultReceivables, defaultEntries, legacyStream)) {
+ assertEquals(200, response.statusCode())
+ assertEquals("", response.body())
+ }
+ coVerify(exactly = 2) { configuration.accounts.get(publicKey) }
+ coVerify(exactly = 2) { configuration.accounts.stream(publicKey) }
+ coVerify(exactly = 1) { configuration.receivables.stream(publicKey, AttoAmount(7UL)) }
+ coVerify(exactly = 1) { configuration.receivables.stream(publicKey, AttoAmount(1UL)) }
+ coVerify(exactly = 1) { configuration.entries.stream(publicKey, AttoHeight(2UL), AttoHeight(5UL)) }
+ coVerify(exactly = 1) { configuration.entries.stream(publicKey, AttoHeight(1UL), null) }
+ coVerify(exactly = 1) { configuration.transactions.stream(publicKey, AttoHeight(1UL), AttoHeight.MAX) }
+ }
+ }
+ }
+
+ @Test
+ fun `HTTP account and stream responses serialize address only while legacy payload stays unchanged`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val key = AttoPublicKey(ByteArray(32) { 1 })
+ val otherKey = AttoPublicKey(ByteArray(32) { 2 })
+ val address = AttoAddress(AttoAlgorithm.V1, key)
+ val algorithm = AttoAlgorithm.V1
+ val version = 0U.toAttoVersion()
+ val timestamp = AttoInstant.now()
+ val hash = AttoHash(ByteArray(32) { 3 })
+ val account =
+ AttoAccount(
+ network = AttoNetwork.LOCAL,
+ version = version,
+ address = AttoAddress(algorithm, key),
+ height = AttoHeight(2UL),
+ balance = AttoAmount(10UL),
+ lastTransactionHash = hash,
+ lastTransactionTimestamp = timestamp,
+ representativeAddress = AttoAddress(algorithm, otherKey),
+ )
+ val receivable =
+ AttoReceivable(
+ network = AttoNetwork.LOCAL,
+ hash = hash,
+ version = version,
+ address = AttoAddress(algorithm, key),
+ timestamp = timestamp,
+ receiverAddress = AttoAddress(algorithm, otherKey),
+ amount = AttoAmount(3UL),
+ )
+ val entry =
+ AttoAccountEntry(
+ hash = hash,
+ address = AttoAddress(algorithm, key),
+ height = AttoHeight(2UL),
+ blockType = AttoBlockType.SEND,
+ subjectAddress = AttoAddress(algorithm, otherKey),
+ previousBalance = AttoAmount(13UL),
+ balance = AttoAmount(10UL),
+ timestamp = timestamp,
+ )
+ val block =
+ AttoSendBlock(
+ network = AttoNetwork.LOCAL,
+ version = version,
+ address = AttoAddress(algorithm, key),
+ height = AttoHeight(2UL),
+ balance = AttoAmount(10UL),
+ timestamp = timestamp,
+ previous = hash,
+ receiverAddress = AttoAddress(algorithm, otherKey),
+ amount = AttoAmount(3UL),
+ )
+ val transaction = AttoTransaction(block, AttoSignature(ByteArray(AttoSignature.SIZE)), AttoWork(ByteArray(AttoWork.SIZE)))
+ coEvery { configuration.accounts.get(key) } returns ResponseEntity.ok(account)
+ coEvery { configuration.accounts.stream(key) } returns flowOf(account)
+ coEvery { configuration.receivables.stream(key, any()) } returns flowOf(receivable)
+ coEvery { configuration.entries.stream(key, any(), any()) } returns flowOf(entry)
+ coEvery { configuration.transactions.stream(key, any(), any()) } returns flowOf(transaction)
+ val encoded = URLEncoder.encode(address.toString(), StandardCharsets.UTF_8)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val responses =
+ listOf("", "/stream", "/receivables/stream", "/entries/stream", "/transactions/stream")
+ .map { suffix -> get(client, "$baseUrl/v2/accounts/$encoded$suffix") }
+ val legacy = get(client, "$baseUrl/accounts/$key")
+
+ // Then
+ for ((index, response) in responses.withIndex()) {
+ assertEquals(200, response.statusCode())
+ assertFalse(response.body().contains("publicKey", ignoreCase = true))
+ assertFalse(response.body().contains("\"algorithm\""))
+ saveEvidence("response-$index.json", response.body())
+ val record = Json.parseToJsonElement(response.body().trim()).jsonObject
+ val identity = if (index == 4) record.getValue("block").jsonObject else record
+ assertEquals("\"$address\"", identity.getValue("address").toString())
+ val mediaType = response.headers().firstValue("Content-Type").orElse("")
+ assertTrue(mediaType.startsWith(if (index == 0) "application/json" else "application/x-ndjson"))
+ }
+ assertEquals(200, legacy.statusCode())
+ saveEvidence("legacy-account.json", legacy.body())
+ assertTrue(legacy.body().contains("publicKey"))
+ assertTrue(legacy.body().contains("representativePublicKey"))
+ }
+ }
+ }
+
+ @Test
+ fun `invalid and double encoded addresses fail binding without calling account handlers`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 }))
+ val encodedAddress = URLEncoder.encode(address.toString(), StandardCharsets.UTF_8)
+ val doubleEncodedAddress = URLEncoder.encode(encodedAddress, StandardCharsets.UTF_8)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val invalid = get(client, "$baseUrl/v2/accounts/not-an-address")
+ val doubleEncoded = get(client, "$baseUrl/v2/accounts/$doubleEncodedAddress")
+
+ // Then
+ assertEquals(400, invalid.statusCode())
+ assertEquals(400, doubleEncoded.statusCode())
+ coVerify(exactly = 0) { configuration.accounts.get(any()) }
+ }
+ }
+ }
+
+ @Test
+ fun `generated OpenAPI shows address responses and hides public key routes`() {
+ // Given
+ withServer { baseUrl, _ ->
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val response = get(client, "$baseUrl/v3/api-docs")
+
+ // Then
+ assertEquals(200, response.statusCode())
+ saveEvidence("openapi.json", response.body())
+ val document = Json.parseToJsonElement(response.body()).jsonObject
+ val paths = document.getValue("paths").jsonObject
+ for (suffix in listOf("", "/stream", "/receivables/stream", "/entries/stream", "/transactions/stream")) {
+ assertTrue(paths.containsKey("/v2/accounts/{address}$suffix"))
+ assertFalse(paths.containsKey("/accounts/{publicKey}$suffix"))
+ }
+ assertFalse(paths.getValue("/v2/transactions").jsonObject.containsKey("get"))
+ assertTrue(paths.getValue("/v2/transactions").jsonObject.containsKey("post"))
+ assertTrue(paths.getValue("/v2/transactions/stream").jsonObject.containsKey("get"))
+ assertFalse(paths.getValue("/v2/transactions/stream").jsonObject.containsKey("post"))
+ assertTrue(paths.filterKeys { it.endsWith("/stream") }.keys.all { it.startsWith("/v2/") })
+ for (path in listOf("/transactions", "/v2/transactions")) {
+ val publication =
+ paths
+ .getValue(path)
+ .jsonObject
+ .getValue("post")
+ .jsonObject
+ val parameters = publication.getValue("parameters") as JsonArray
+ val deduplicate = parameters.map { it.jsonObject }.single { it.getValue("name").jsonPrimitive.content == "deduplicate" }
+ assertEquals(
+ "When true, reuse a stored confirmation or an existing pending publication for the same transaction hash. " +
+ "This does not deduplicate payment attempts with different transaction hashes.",
+ deduplicate.getValue("description").jsonPrimitive.content,
+ )
+ }
+ assertEquals(
+ "getAccountsByAddresses",
+ paths
+ .getValue("/v2/accounts")
+ .jsonObject
+ .getValue("post")
+ .jsonObject
+ .getValue("operationId")
+ .jsonPrimitive.content,
+ )
+ val batchSchema =
+ paths
+ .getValue("/v2/accounts")
+ .jsonObject
+ .getValue("post")
+ .jsonObject
+ .getValue("responses")
+ .jsonObject
+ .getValue("200")
+ .jsonObject
+ .getValue("content")
+ .jsonObject
+ .getValue("application/json")
+ .jsonObject
+ .getValue("schema")
+ .jsonObject
+ assertEquals("array", batchSchema["type"]?.jsonPrimitive?.content, batchSchema.toString())
+ assertEquals(
+ "#/components/schemas/AttoAccount",
+ batchSchema
+ .getValue("items")
+ .jsonObject
+ .getValue("\$ref")
+ .jsonPrimitive.content,
+ )
+ val publicationSchema =
+ paths
+ .getValue("/transactions")
+ .jsonObject
+ .getValue("post")
+ .jsonObject
+ .getValue(
+ "requestBody",
+ ).jsonObject
+ .getValue("content")
+ .jsonObject
+ .getValue("application/json")
+ .jsonObject
+ .getValue("schema")
+ .jsonObject
+ assertEquals("#/components/schemas/AttoTransaction", publicationSchema.getValue("\$ref").jsonPrimitive.content)
+ val schemas =
+ document
+ .getValue("components")
+ .jsonObject
+ .getValue("schemas")
+ .jsonObject
+
+ fun propertiesOf(schema: JsonObject): Map {
+ val inherited = mutableMapOf()
+ (schema["allOf"] as? JsonArray)?.forEach { part ->
+ val objectPart = part.jsonObject
+ val reference = objectPart["\$ref"]?.jsonPrimitive?.content
+ val resolved = if (reference == null) objectPart else schemas.getValue(reference.substringAfterLast('/')).jsonObject
+ inherited.putAll(propertiesOf(resolved))
+ }
+ (schema["properties"] as? JsonObject)?.let { inherited.putAll(it) }
+ return inherited
+ }
+ for (name in listOf(
+ "AttoAccount",
+ "AttoReceivable",
+ "AttoAccountEntry",
+ "AttoOpenBlock",
+ "AttoReceiveBlock",
+ "AttoSendBlock",
+ "AttoChangeBlock",
+ )) {
+ val properties = propertiesOf(schemas.getValue(name).jsonObject)
+ assertTrue(properties.containsKey("address"), name)
+ assertFalse(properties.keys.any { it.endsWith("publicKey", ignoreCase = true) }, name)
+ }
+ val visited = mutableSetOf()
+
+ fun verifyReachableSchema(element: JsonElement) {
+ when (element) {
+ is JsonObject -> {
+ val properties = element["properties"] as? JsonObject
+ assertFalse(properties?.keys?.any { it.endsWith("publicKey", ignoreCase = true) } == true)
+ element["\$ref"]?.jsonPrimitive?.content?.let { reference ->
+ val name = reference.substringAfterLast('/')
+ assertFalse(name == "AttoPublicKey")
+ if (visited.add(name)) verifyReachableSchema(schemas.getValue(name))
+ }
+ element.values.forEach { verifyReachableSchema(it) }
+ }
+
+ is JsonArray -> {
+ element.forEach { verifyReachableSchema(it) }
+ }
+
+ else -> {
+ Unit
+ }
+ }
+ }
+ paths.filterKeys { it.startsWith("/v2/") }.values.forEach { verifyReachableSchema(it) }
+ for ((name, expectedTypes) in mapOf(
+ "AttoBlock" to setOf("OPEN", "RECEIVE", "SEND", "CHANGE"),
+ "AttoOpenBlock" to setOf("OPEN"),
+ "AttoReceiveBlock" to setOf("RECEIVE"),
+ "AttoSendBlock" to setOf("SEND"),
+ "AttoChangeBlock" to setOf("CHANGE"),
+ )) {
+ val schema = schemas.getValue(name).jsonObject
+ val type = propertiesOf(schema).getValue("type").jsonObject
+ assertEquals(expectedTypes, (type.getValue("enum") as JsonArray).map { it.jsonPrimitive.content }.toSet())
+ assertTrue((schema.getValue("required") as JsonArray).any { it.jsonPrimitive.content == "type" }, name)
+ }
+ val baseBlock = schemas.getValue("AttoBlock").jsonObject
+ assertFalse(baseBlock.containsKey("oneOf"))
+ assertFalse(baseBlock.containsKey("anyOf"))
+ val discriminator =
+ schemas
+ .getValue("AttoBlock")
+ .jsonObject
+ .getValue("discriminator")
+ .jsonObject
+ assertEquals("\"type\"", discriminator.getValue("propertyName").toString())
+ assertEquals(setOf("OPEN", "RECEIVE", "SEND", "CHANGE"), discriminator.getValue("mapping").jsonObject.keys)
+ discriminator.getValue("mapping").jsonObject.values.forEach { target ->
+ assertTrue(schemas.containsKey(target.jsonPrimitive.content.substringAfterLast('/')))
+ }
+ }
+ }
+ }
+
+ @Test
+ fun `v2 flushes blank heartbeats while legacy delays its first byte and both complete once`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val account = LegacyHttpFixtures.account
+ val subscriptions = AtomicInteger()
+ coEvery { configuration.accounts.stream(account.address.publicKey) } returns
+ flow {
+ subscriptions.incrementAndGet()
+ delay(2200)
+ emit(account)
+ }
+ val encoded = URLEncoder.encode(account.address.toString(), StandardCharsets.UTF_8)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val canonical = get(client, "$baseUrl/v2/accounts/$encoded/stream")
+ val legacy = get(client, "$baseUrl/accounts/${account.address.publicKey}/stream")
+
+ // Then
+ assertEquals(200, canonical.statusCode())
+ assertTrue(canonical.body().startsWith("\n\n"), canonical.body())
+ assertEquals(1, canonical.body().lineSequence().count { it.isNotBlank() })
+ assertTrue(legacy.body().startsWith("{"), legacy.body())
+ assertEquals(1, legacy.body().lineSequence().count { it.isNotBlank() })
+ assertEquals(2, subscriptions.get())
+ }
+ }
+ }
+
+ @Test
+ fun `disconnecting a v2 heartbeat stream cancels the single upstream collection`(): Unit =
+ runBlocking {
+ // Given
+ withServer { baseUrl, configuration ->
+ val address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 }))
+ val subscriptions = AtomicInteger()
+ val cancelled = CompletableDeferred()
+ coEvery { configuration.accounts.stream(address.publicKey) } returns
+ flow {
+ subscriptions.incrementAndGet()
+ try {
+ awaitCancellation()
+ } finally {
+ cancelled.complete(Unit)
+ }
+ }
+ val encoded = URLEncoder.encode(address.toString(), StandardCharsets.UTF_8)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val response =
+ client.send(
+ HttpRequest.newBuilder(URI("$baseUrl/v2/accounts/$encoded/stream")).GET().build(),
+ HttpResponse.BodyHandlers.ofInputStream(),
+ )
+ response.body().use { assertEquals('\n'.code, it.read()) }
+
+ // Then
+ runBlocking { withTimeout(5000) { cancelled.await() } }
+ assertEquals(1, subscriptions.get())
+ }
+ }
+ }
+
+ @Test
+ fun `all versioned stream aliases return canonical models and legacy aliases preserve their fields`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ fun fixture(name: String) = checkNotNull(javaClass.getResource("/legacy-http/$name.json")).readText()
+ val account = LegacyHttpFixtures.account
+ val entry = LegacyHttpFixtures.entry
+ val receivable = LegacyHttpFixtures.receivable
+ val transaction = LegacyHttpFixtures.transaction("send")
+ coEvery { configuration.accounts.stream() } returns flowOf(account)
+ coEvery { configuration.accounts.stream(any()) } returns flowOf(account)
+ coEvery { configuration.entries.stream() } returns flowOf(entry)
+ coEvery { configuration.entries.stream(any()) } returns flowOf(entry)
+ coEvery { configuration.entries.streamMultiple(any()) } returns flowOf(entry)
+ coEvery { configuration.receivables.stream(any(), any()) } returns flowOf(receivable)
+ coEvery { configuration.transactions.stream() } returns flowOf(transaction)
+ coEvery { configuration.transactions.stream(any()) } returns flowOf(transaction)
+ coEvery { configuration.transactions.streamMultiple(any()) } returns flowOf(transaction)
+ coEvery { configuration.publication.publishAndStream(any(), any(), any()) } returns flowOf(transaction)
+ val search = "{\"addresses\":[\"${account.address}\"]}"
+ val range = "{\"search\":[{\"address\":\"${account.address}\",\"fromHeight\":1,\"toHeight\":2}]}"
+ val routes =
+ listOf(
+ Triple("/accounts/stream", null, "account"),
+ Triple("/accounts/stream", search, "account"),
+ Triple("/accounts/receivables/stream", search, "receivable"),
+ Triple("/accounts/entries/stream", null, "entry"),
+ Triple("/accounts/entries/stream", range, "entry"),
+ Triple("/accounts/entries/${entry.hash}/stream", null, "entry"),
+ Triple("/accounts/transactions/stream", range, "send"),
+ Triple("/transactions/stream", null, "send"),
+ Triple("/transactions/${transaction.hash}/stream", null, "send"),
+ Triple("/transactions/stream", fixture("send"), "send"),
+ )
+ HttpClient.newHttpClient().use { client ->
+ for ((path, body, expected) in routes) {
+ fun request(prefix: String): HttpResponse {
+ val resolvedPath = if (prefix == "/v2" && path == "/transactions/stream" && body != null) "/transactions" else path
+ val builder = HttpRequest.newBuilder(URI("$baseUrl$prefix$resolvedPath")).timeout(Duration.ofSeconds(5))
+ if (body ==
+ null
+ ) {
+ builder.GET()
+ } else {
+ builder.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body))
+ }
+ return client.send(builder.build(), HttpResponse.BodyHandlers.ofString())
+ }
+
+ // When
+ val canonical = request("/v2")
+ val legacy = request("")
+
+ // Then
+ assertEquals(200, canonical.statusCode(), path + canonical.body())
+ assertEquals(200, legacy.statusCode(), path + legacy.body())
+ assertFalse(canonical.body().contains("publicKey", ignoreCase = true), path)
+ assertFalse(canonical.body().contains("\"algorithm\""), path)
+ assertEquals(fixture(expected), legacy.body().trim(), path)
+ }
+ }
+ }
+ }
+
+ @Test
+ fun `publication uses the v2 collection path and flushes heartbeats while legacy publication bytes stay unchanged`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val body = checkNotNull(javaClass.getResource("/legacy-http/send.json")).readText()
+ val transaction = LegacyHttpFixtures.transaction("send")
+ val subscriptions = AtomicInteger()
+ coEvery { configuration.publication.publishAndStream(any(), any(), any()) } returns
+ flow {
+ subscriptions.incrementAndGet()
+ delay(1200)
+ emit(transaction)
+ }
+ HttpClient.newHttpClient().use { client ->
+ fun publish(path: String): HttpResponse =
+ client.send(
+ HttpRequest
+ .newBuilder(URI("$baseUrl$path"))
+ .timeout(Duration.ofSeconds(5))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(body))
+ .build(),
+ HttpResponse.BodyHandlers.ofString(),
+ )
+
+ // When
+ val canonical = publish("/v2/transactions")
+ val legacy = publish("/transactions/stream")
+ val removed = publish("/v2/transactions/stream")
+
+ // Then
+ assertEquals(200, canonical.statusCode())
+ assertTrue(canonical.body().startsWith("\n"), canonical.body())
+ assertFalse(canonical.body().contains("publicKey", ignoreCase = true))
+ assertEquals(200, legacy.statusCode())
+ assertTrue(legacy.body().startsWith("{"), legacy.body())
+ assertEquals(Json.parseToJsonElement(body), Json.parseToJsonElement(legacy.body().trim()))
+ assertEquals(405, removed.statusCode())
+ assertEquals(405, get(client, "$baseUrl/v2/transactions").statusCode())
+ assertEquals(2, subscriptions.get())
+ }
+ }
+ }
+
+ @Test
+ fun `finite account batches preserve canonical and legacy response contracts`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ val account = LegacyHttpFixtures.account
+ val search = "{\"addresses\":[\"${account.address}\"]}"
+ every { configuration.accounts.get(any()) } returns flowOf(account)
+ HttpClient.newHttpClient().use { client ->
+ // When
+ val canonical = post(client, "$baseUrl/v2/accounts", search)
+ val legacy = post(client, "$baseUrl/accounts", search)
+ every { configuration.accounts.get(any()) } returns emptyFlow()
+ val emptyCanonical = post(client, "$baseUrl/v2/accounts", "{\"addresses\":[]}")
+ val emptyLegacy = post(client, "$baseUrl/accounts", "{\"addresses\":[]}")
+
+ // Then
+ assertEquals(200, canonical.statusCode())
+ assertTrue(
+ canonical
+ .headers()
+ .firstValue("Content-Type")
+ .orElse("")
+ .startsWith("application/json"),
+ )
+ assertEquals(JsonArray(listOf(Json.encodeToJsonElement(account))), Json.parseToJsonElement(canonical.body()))
+ assertFalse(canonical.body().contains("publicKey", ignoreCase = true))
+ assertEquals(200, legacy.statusCode())
+ val oldRecord = checkNotNull(javaClass.getResource("/legacy-http/account.json")).readText()
+ assertEquals("[$oldRecord]", legacy.body())
+ assertEquals(200, emptyCanonical.statusCode())
+ assertEquals("[]", emptyCanonical.body())
+ assertEquals(200, emptyLegacy.statusCode())
+ assertEquals("[]", emptyLegacy.body())
+ }
+ }
+ }
+
+ @Test
+ fun `legacy publication accepts key-only blocks while v2 requires addresses`() {
+ // Given
+ withServer { baseUrl, configuration ->
+ HttpClient.newHttpClient().use { client ->
+ for (name in listOf("open", "receive", "send", "change")) {
+ val oldBody = checkNotNull(javaClass.getResource("/legacy-http/$name.json")).readText()
+ val oldRecord = Json.parseToJsonElement(oldBody).jsonObject
+ val block = oldRecord.getValue("block").jsonObject
+ val keysOnly =
+ JsonObject(
+ oldRecord + (
+ "block" to
+ JsonObject(
+ block.filterKeys {
+ it !in setOf("address", "receiverAddress", "representativeAddress") &&
+ (name != "open" || it != "height")
+ },
+ )
+ ),
+ )
+ val transaction = LegacyHttpFixtures.transaction(name)
+ coEvery { configuration.publication.publish(any(), any(), any()) } returns transaction
+ coEvery { configuration.publication.publishAndStream(any(), any(), any()) } returns flowOf(transaction)
+
+ // When
+ val scalar = post(client, "$baseUrl/transactions", keysOnly.toString())
+ val streamed = post(client, "$baseUrl/transactions/stream", keysOnly.toString())
+ val rejected = post(client, "$baseUrl/v2/transactions", keysOnly.toString())
+ val canonical = post(client, "$baseUrl/v2/transactions", Json.encodeToJsonElement(transaction).toString())
+
+ // Then
+ assertEquals(200, scalar.statusCode(), name + scalar.body())
+ assertEquals(oldBody, scalar.body(), name)
+ assertEquals(200, streamed.statusCode(), name + streamed.body())
+ assertEquals(oldBody, streamed.body().trim(), name)
+ assertEquals(400, rejected.statusCode(), name + rejected.body())
+ assertEquals(200, canonical.statusCode(), name + canonical.body())
+ assertEquals(Json.encodeToJsonElement(transaction), Json.parseToJsonElement(canonical.body().trim()), name)
+ val role =
+ when (name) {
+ "open", "change" -> "representativeAddress"
+ "send" -> "receiverAddress"
+ else -> null
+ }
+ if (role != null) {
+ val missingRole = JsonObject(oldRecord + ("block" to JsonObject(block - role)))
+ assertEquals(400, post(client, "$baseUrl/v2/transactions", missingRole.toString()).statusCode(), name)
+ }
+ }
+ }
+ }
+ }
+
+ private fun post(
+ client: HttpClient,
+ url: String,
+ body: String,
+ ): HttpResponse =
+ client.send(
+ HttpRequest
+ .newBuilder(URI(url))
+ .timeout(Duration.ofSeconds(5))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(body))
+ .build(),
+ HttpResponse.BodyHandlers.ofString(),
+ )
+
+ private fun saveEvidence(
+ name: String,
+ body: String,
+ ) {
+ val directory = System.getenv("ATTO_ADDRESS_EVIDENCE_DIR") ?: return
+ Files.writeString(Files.createDirectories(Path.of(directory)).resolve(name), body)
+ }
+
+ private fun get(
+ client: HttpClient,
+ url: String,
+ ): HttpResponse =
+ client.send(
+ HttpRequest
+ .newBuilder(URI(url))
+ .timeout(Duration.ofSeconds(5))
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofString(),
+ )
+
+ private fun withServer(test: (String, RoutesConfiguration) -> Unit) {
+ AnnotationConfigReactiveWebApplicationContext().use { context ->
+ context.register(RoutesConfiguration::class.java)
+ context.refresh()
+ val server = NettyReactiveWebServerFactory(0).getWebServer(WebHttpHandlerBuilder.applicationContext(context).build())
+ server.start()
+ try {
+ test("http://127.0.0.1:${server.port}", context.getBean(RoutesConfiguration::class.java))
+ } finally {
+ server.stop()
+ }
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ @EnableWebFlux
+ @Import(
+ AttoConversionsAutoConfiguration::class,
+ SpringDocConfiguration::class,
+ SpringDocKotlinxConfiguration::class,
+ SpringDocWebFluxConfiguration::class,
+ SpringDocConfigProperties::class,
+ AttoSpringDocOpenApiAutoConfiguration::class,
+ )
+ class RoutesConfiguration : WebFluxConfigurer {
+ override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
+ HttpSerializationConfiguration().configureHttpMessageCodecs(configurer)
+ }
+
+ val accounts =
+ spyk(AccountController(AccountQueries(mockk(), mockk()))).apply {
+ coEvery { get(any()) } returns ResponseEntity.notFound().build()
+ coEvery { stream(any()) } returns emptyFlow()
+ }
+ val receivables =
+ spyk(ReceivableController(ReceivableQueries(mockk()))).apply {
+ coEvery { stream(any(), any()) } returns
+ emptyFlow()
+ }
+ val entries =
+ spyk(AccountEntryController(AccountEntryQueries(mockk()))).apply {
+ coEvery { stream(any(), any(), any()) } returns
+ emptyFlow()
+ }
+ val transactions =
+ spyk(TransactionController(TransactionQueries(mockk()))).apply {
+ coEvery { stream(any(), any(), any()) } returns
+ emptyFlow()
+ }
+
+ val publication = spyk(TransactionPublicationController(mockk(), mockk(), mockk(), mockk()))
+
+ @Bean
+ fun publicationController(): TransactionPublicationController = publication
+
+ @Bean
+ fun accountController(): AccountController = accounts
+
+ @Bean
+ fun receivableController(): ReceivableController = receivables
+
+ @Bean
+ fun entryController(): AccountEntryController = entries
+
+ @Bean
+ fun transactionController(): TransactionController = transactions
+ }
+}
diff --git a/src/test/kotlin/cash/atto/node/NodeController.kt b/src/test/kotlin/cash/atto/node/NodeController.kt
index edb0f4db..35fa4124 100644
--- a/src/test/kotlin/cash/atto/node/NodeController.kt
+++ b/src/test/kotlin/cash/atto/node/NodeController.kt
@@ -3,12 +3,14 @@ package cash.atto.node
import cash.atto.commons.AttoPublicKey
import cash.atto.node.network.NetworkProcessor
import cash.atto.node.network.NodeConnectionManager
+import io.swagger.v3.oas.annotations.Hidden
import org.springframework.context.annotation.Profile
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
+@Hidden
@RestController
@RequestMapping("/nodes")
@Profile("default")
diff --git a/src/test/kotlin/cash/atto/node/OpenAPITest.kt b/src/test/kotlin/cash/atto/node/OpenAPITest.kt
index 1ab381a6..8a12c48b 100644
--- a/src/test/kotlin/cash/atto/node/OpenAPITest.kt
+++ b/src/test/kotlin/cash/atto/node/OpenAPITest.kt
@@ -1,5 +1,10 @@
package cash.atto.node
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
@@ -34,14 +39,159 @@ class OpenAPITest {
.expectBody()
.jsonPath("$.paths['/transactions'].post.responses['200']")
.exists()
- .jsonPath("$.paths['/transactions/stream'].post.responses['200']")
+ .jsonPath("$.paths['/v2/transactions'].post.responses['200']")
.exists()
- .jsonPath("$.paths['/transactions/stream'].get.responses['200']")
+ .jsonPath("$.paths['/v2/transactions/stream'].get.responses['200']")
.exists()
.jsonPath("$.paths['/transactions/{hash}'].get.responses['200']")
.exists()
}
+ @Test
+ fun `address based v2 routes replace public key routes in generated OpenAPI`() {
+ // Given
+ val request = webTestClient.get().uri("/v3/api-docs")
+
+ // When
+ val response = request.exchange()
+
+ // Then
+ response
+ .expectStatus()
+ .isOk
+ .expectBody()
+ .jsonPath("$.paths['/accounts/{publicKey}']")
+ .doesNotExist()
+ .jsonPath("$.paths['/accounts/{publicKey}/stream']")
+ .doesNotExist()
+ .jsonPath("$.paths['/accounts/{publicKey}/receivables/stream']")
+ .doesNotExist()
+ .jsonPath("$.paths['/accounts/{publicKey}/entries/stream']")
+ .doesNotExist()
+ .jsonPath("$.paths['/accounts/{publicKey}/transactions/stream']")
+ .doesNotExist()
+ .jsonPath("$.paths['/v2/accounts/{address}']")
+ .exists()
+ .jsonPath("$.paths['/v2/accounts/{address}/stream']")
+ .exists()
+ .jsonPath("$.paths['/v2/accounts/{address}/receivables/stream']")
+ .exists()
+ .jsonPath("$.paths['/v2/accounts/{address}/entries/stream']")
+ .exists()
+ .jsonPath("$.paths['/v2/accounts/{address}/transactions/stream']")
+ .exists()
+ }
+
+ @Test
+ fun `production operations have descriptive and unique IDs without test helper endpoints`() {
+ // Given
+ val request = webTestClient.get().uri("/v3/api-docs")
+
+ // When
+ val body =
+ request
+ .exchange()
+ .expectStatus()
+ .isOk
+ .expectBody(String::class.java)
+ .returnResult()
+ .responseBody
+ val paths =
+ Json
+ .parseToJsonElement(checkNotNull(body))
+ .jsonObject
+ .getValue("paths")
+ .jsonObject
+
+ // Then
+ val expectedOperations =
+ listOf(
+ Triple("/accounts", "post", "getLegacyAccountsByAddresses"),
+ Triple("/v2/accounts", "post", "getAccountsByAddresses"),
+ Triple("/v2/accounts/{address}", "get", "getAccountByAddress"),
+ Triple("/v2/accounts/stream", "get", "streamAllAccounts"),
+ Triple("/v2/accounts/stream", "post", "streamAccountsByAddresses"),
+ Triple("/v2/accounts/{address}/stream", "get", "streamAccountByAddress"),
+ Triple("/v2/accounts/receivables/stream", "post", "streamReceivablesByAddresses"),
+ Triple("/v2/accounts/{address}/receivables/stream", "get", "streamReceivablesByAddress"),
+ Triple("/v2/accounts/entries/stream", "get", "streamAllAccountEntries"),
+ Triple("/v2/accounts/entries/stream", "post", "streamAccountEntriesByHeightRanges"),
+ Triple("/v2/accounts/entries/{hash}/stream", "get", "streamAccountEntryByHash"),
+ Triple("/v2/accounts/{address}/entries/stream", "get", "streamAccountEntriesByAddress"),
+ Triple("/v2/accounts/transactions/stream", "post", "streamTransactionsByHeightRanges"),
+ Triple("/v2/accounts/{address}/transactions/stream", "get", "streamTransactionsByAddress"),
+ Triple("/v2/transactions/stream", "get", "streamAllTransactions"),
+ Triple("/v2/transactions/{hash}/stream", "get", "streamTransactionByHash"),
+ Triple("/v2/transactions", "post", "publishTransactionAndWaitForConfirmation"),
+ Triple("/transactions", "post", "publishLegacyTransactionAndWaitForConfirmation"),
+ Triple("/transactions/{hash}", "get", "getTransactionByHash"),
+ Triple("/vote-weights/{address}", "get", "getVoterWeightByAddress"),
+ Triple("/instants/{clientInstant}", "get", "getTimeDifference"),
+ )
+ for ((path, method, operationId) in expectedOperations) {
+ assertEquals(
+ operationId,
+ paths
+ .getValue(path)
+ .jsonObject
+ .getValue(method)
+ .jsonObject
+ .getValue("operationId")
+ .jsonPrimitive.content,
+ )
+ }
+ val batchSchema =
+ paths
+ .getValue("/v2/accounts")
+ .jsonObject
+ .getValue("post")
+ .jsonObject
+ .getValue("responses")
+ .jsonObject
+ .getValue("200")
+ .jsonObject
+ .getValue("content")
+ .jsonObject
+ .getValue("application/json")
+ .jsonObject
+ .getValue("schema")
+ .jsonObject
+ assertEquals("array", batchSchema.getValue("type").jsonPrimitive.content)
+ assertEquals(
+ "#/components/schemas/AttoAccount",
+ batchSchema
+ .getValue("items")
+ .jsonObject
+ .getValue("\$ref")
+ .jsonPrimitive.content,
+ )
+ val methods = setOf("get", "post", "put", "patch", "delete", "head", "options", "trace")
+ val operationIds =
+ paths.values.flatMap { path ->
+ path.jsonObject
+ .filterKeys { it in methods }
+ .values
+ .map {
+ it.jsonObject
+ .getValue("operationId")
+ .jsonPrimitive.content
+ }
+ }
+ assertEquals(operationIds.size, operationIds.toSet().size, operationIds.toString())
+ assertEquals(expectedOperations.map { it.third }.toSet(), operationIds.toSet())
+ for (path in listOf(
+ "/nodes/peers",
+ "/nodes/bootstrap",
+ "/unchecked-transactions",
+ "/unchecked-transactions/discoveries/gap",
+ "/unchecked-transactions/discoveries/last",
+ "/unchecked-transactions/discoveries/flush",
+ "/unchecked-transactions/discoveries/settle",
+ )) {
+ assertFalse(paths.containsKey(path), path)
+ }
+ }
+
@Test
fun `GET health probes are reachable`() {
// Given
diff --git a/src/test/kotlin/cash/atto/node/account/AccountCachedRepositoryTest.kt b/src/test/kotlin/cash/atto/node/account/AccountCachedRepositoryTest.kt
index 8b1613b3..01baa9cd 100644
--- a/src/test/kotlin/cash/atto/node/account/AccountCachedRepositoryTest.kt
+++ b/src/test/kotlin/cash/atto/node/account/AccountCachedRepositoryTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.account
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -262,8 +263,7 @@ class AccountCachedRepositoryTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height.toULong().toAttoHeight(),
balance = AttoAmount(height.toULong() * 100UL),
timestamp = AttoInstant.now() + height.milliseconds,
diff --git a/src/test/kotlin/cash/atto/node/account/AccountControllerTest.kt b/src/test/kotlin/cash/atto/node/account/AccountQueriesTest.kt
similarity index 82%
rename from src/test/kotlin/cash/atto/node/account/AccountControllerTest.kt
rename to src/test/kotlin/cash/atto/node/account/AccountQueriesTest.kt
index cc147058..a2a7d125 100644
--- a/src/test/kotlin/cash/atto/node/account/AccountControllerTest.kt
+++ b/src/test/kotlin/cash/atto/node/account/AccountQueriesTest.kt
@@ -40,12 +40,12 @@ import org.junit.jupiter.api.Test
import java.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
-class AccountControllerTest {
+class AccountQueriesTest {
private val repository = mockk()
- private val controller = AccountController(repository, mockk())
+ private val queries = AccountQueries(repository, mockk())
@Test
- fun `subscribes before starting a blocked database read and retains a concurrent update`() =
+ fun `subscribes before starting a blocked database read and retains a concurrent update`(): Unit =
runTest {
// Given
val snapshot = opened().updatedAccount
@@ -53,7 +53,7 @@ class AccountControllerTest {
val finishRead = CompletableDeferred()
lateinit var publication: Deferred
every { repository.findAllById(any()) } answers {
- publication = backgroundScope.async(start = CoroutineStart.UNDISPATCHED) { controller.process(update) }
+ publication = backgroundScope.async(start = CoroutineStart.UNDISPATCHED) { queries.process(update) }
flow {
finishRead.await()
emit(snapshot)
@@ -62,7 +62,7 @@ class AccountControllerTest {
val accounts = mutableListOf()
// When
- backgroundScope.launch { controller.stream(snapshot.publicKey).toList(accounts) }
+ backgroundScope.launch { queries.stream(snapshot.publicKey).toList(accounts) }
runCurrent()
// Then
@@ -79,7 +79,7 @@ class AccountControllerTest {
}
@Test
- fun `drops equal and older snapshot overlaps and delayed updates after newer live state`() =
+ fun `drops equal and older snapshot overlaps and delayed updates after newer live state`(): Unit =
runTest {
// Given
val opened = opened()
@@ -94,22 +94,22 @@ class AccountControllerTest {
finishRead.await()
}
val accounts = mutableListOf()
- backgroundScope.launch { controller.stream(third.updatedAccount.publicKey).toList(accounts) }
+ backgroundScope.launch { queries.stream(third.updatedAccount.publicKey).toList(accounts) }
runCurrent()
// When
- val older = backgroundScope.async { controller.process(second) }
- val equal = backgroundScope.async { controller.process(third) }
- val newer = backgroundScope.async { controller.process(fourth) }
+ val older = backgroundScope.async { queries.process(second) }
+ val equal = backgroundScope.async { queries.process(third) }
+ val newer = backgroundScope.async { queries.process(fourth) }
runCurrent()
finishRead.complete(Unit)
runCurrent()
older.await()
equal.await()
newer.await()
- controller.process(third)
- controller.process(second)
- controller.process(fifth)
+ queries.process(third)
+ queries.process(second)
+ queries.process(fifth)
runCurrent()
// Then
@@ -117,17 +117,17 @@ class AccountControllerTest {
}
@Test
- fun `streams the first committed update for an unopened account`() =
+ fun `streams the first committed update for an unopened account`(): Unit =
runTest {
// Given
val opened = opened()
every { repository.findAllById(any()) } returns emptyFlow()
val accounts = mutableListOf()
- backgroundScope.launch { controller.stream(opened.updatedAccount.publicKey).toList(accounts) }
+ backgroundScope.launch { queries.stream(opened.updatedAccount.publicKey).toList(accounts) }
runCurrent()
// When
- controller.process(opened)
+ queries.process(opened)
runCurrent()
// Then
@@ -135,26 +135,26 @@ class AccountControllerTest {
}
@Test
- fun `each collection of the same flow owns its forward heights`() =
+ fun `each collection of the same flow owns its forward heights`(): Unit =
runTest {
// Given
val snapshot = opened().updatedAccount
val second = received(snapshot)
val third = received(second.updatedAccount)
every { repository.findAllById(any()) } returns flowOf(snapshot)
- val stream = controller.stream(snapshot.publicKey)
+ val stream = queries.stream(snapshot.publicKey)
val firstAccounts = mutableListOf()
val secondAccounts = mutableListOf()
val first = backgroundScope.launch { stream.toList(firstAccounts) }
runCurrent()
- controller.process(second)
+ queries.process(second)
runCurrent()
// When
backgroundScope.launch { stream.toList(secondAccounts) }
runCurrent()
first.cancelAndJoin()
- controller.process(third)
+ queries.process(third)
runCurrent()
// Then
@@ -163,7 +163,7 @@ class AccountControllerTest {
}
@Test
- fun `cancelling a blocked snapshot releases the live publisher and cancels the database read`() =
+ fun `cancelling a blocked snapshot releases the live publisher and cancels the database read`(): Unit =
runTest {
// Given
val snapshot = opened().updatedAccount
@@ -178,9 +178,9 @@ class AccountControllerTest {
}
}
val accounts = mutableListOf()
- val collection = backgroundScope.launch { controller.stream(snapshot.publicKey).toList(accounts) }
+ val collection = backgroundScope.launch { queries.stream(snapshot.publicKey).toList(accounts) }
runCurrent()
- val publication = backgroundScope.async { controller.process(received(snapshot)) }
+ val publication = backgroundScope.async { queries.process(received(snapshot)) }
runCurrent()
assertFalse(publication.isCompleted)
@@ -195,7 +195,7 @@ class AccountControllerTest {
}
@Test
- fun `filters unrelated live accounts and tracks heights independently for each requested address`() =
+ fun `filters unrelated live accounts and tracks heights independently for each requested address`(): Unit =
runTest {
// Given
val first = opened(1).updatedAccount
@@ -206,13 +206,13 @@ class AccountControllerTest {
every { repository.findAllById(listOf(first.publicKey, second.publicKey)) } returns flowOf(first, second)
val search = AccountSearch(linkedSetOf(first, second).map { AttoAddress(it.algorithm, it.publicKey) }.toSet())
val accounts = mutableListOf()
- backgroundScope.launch { controller.stream(search).toList(accounts) }
+ backgroundScope.launch { queries.stream(search).toList(accounts) }
runCurrent()
// When
- controller.process(unrelated)
- controller.process(firstNext)
- controller.process(secondNext)
+ queries.process(unrelated)
+ queries.process(firstNext)
+ queries.process(secondNext)
runCurrent()
// Then
@@ -226,27 +226,25 @@ class AccountControllerTest {
AttoOpenBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
balance = AttoAmount(100UL),
timestamp = timestamp.toAtto(),
sendHashAlgorithm = AttoAlgorithm.V1,
sendHash = AttoHash(ByteArray(32) { key.toByte() }),
- representativeAlgorithm = AttoAlgorithm.V1,
- representativePublicKey = publicKey,
+ representativeAddress = AttoAddress(AttoAlgorithm.V1, publicKey),
)
val previous =
Account(
publicKey = publicKey,
network = block.network,
version = block.version,
- algorithm = block.algorithm,
+ algorithm = block.address.algorithm,
height = 0,
balance = AttoAmount.MIN,
lastTransactionHash = block.hash,
lastTransactionTimestamp = timestamp,
- representativeAlgorithm = block.representativeAlgorithm,
- representativePublicKey = block.representativePublicKey,
+ representativeAlgorithm = block.representativeAddress.algorithm,
+ representativePublicKey = block.representativeAddress.publicKey,
)
val account = previous.copy(height = 1, balance = block.balance, persistedAt = timestamp, updatedAt = timestamp)
val transaction = Transaction(block, AttoSignature(ByteArray(64)), AttoWork(ByteArray(8)))
@@ -260,8 +258,7 @@ class AccountControllerTest {
AttoReceiveBlock(
version = previous.version,
network = previous.network,
- algorithm = previous.algorithm,
- publicKey = previous.publicKey,
+ address = AttoAddress(previous.algorithm, previous.publicKey),
height = height.toULong().toAttoHeight(),
balance = AttoAmount(height.toULong() * 100UL),
timestamp = timestamp.toAtto(),
diff --git a/src/test/kotlin/cash/atto/node/account/AccountServiceTest.kt b/src/test/kotlin/cash/atto/node/account/AccountServiceTest.kt
index b4b675fc..e33e1d6c 100644
--- a/src/test/kotlin/cash/atto/node/account/AccountServiceTest.kt
+++ b/src/test/kotlin/cash/atto/node/account/AccountServiceTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.account
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -148,8 +149,7 @@ class AccountServiceTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height,
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/account/AddressResponseTest.kt b/src/test/kotlin/cash/atto/node/account/AddressResponseTest.kt
new file mode 100644
index 00000000..d7c820a2
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/account/AddressResponseTest.kt
@@ -0,0 +1,85 @@
+package cash.atto.node.account
+
+import cash.atto.commons.toHex
+import cash.atto.node.account.entry.toLegacyResponse
+import cash.atto.node.receivable.toLegacyResponse
+import cash.atto.node.transaction.toLegacyResponse
+import kotlinx.io.readByteArray
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.encodeToJsonElement
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Test
+
+class AddressResponseTest {
+ // Fixtures were emitted by Commons 8 using the Node HTTP codec settings.
+ private val json =
+ Json {
+ encodeDefaults = true
+ explicitNulls = false
+ ignoreUnknownKeys = true
+ }
+
+ @Test
+ fun `legacy responses match published Commons 8 fields and numbers while canonical models serialize addresses`() {
+ // Given
+ val account = LegacyHttpFixtures.account
+ val entry = LegacyHttpFixtures.entry
+ val receivable = LegacyHttpFixtures.receivable
+
+ // When
+ val legacy =
+ listOf(
+ "account" to json.encodeToJsonElement(account.toLegacyResponse()),
+ "entry" to json.encodeToJsonElement(entry.toLegacyResponse()),
+ "receivable" to json.encodeToJsonElement(receivable.toLegacyResponse()),
+ )
+ val canonical =
+ listOf(
+ json.encodeToJsonElement(account),
+ json.encodeToJsonElement(entry),
+ json.encodeToJsonElement(receivable),
+ )
+
+ // Then
+ legacy.forEach { (name, actual) -> assertEquals(fixture(name), actual.toString(), name) }
+ canonical.forEach { assertCanonicalIdentity(it) }
+ }
+
+ @Test
+ fun `all block variants preserve legacy responses and original binary transaction bytes`() {
+ // Given
+ for (name in listOf("open", "receive", "send", "change")) {
+ val transaction = LegacyHttpFixtures.transaction(name)
+
+ // When
+ val legacy = json.encodeToJsonElement(transaction.toLegacyResponse())
+ val canonical = json.encodeToJsonElement(transaction)
+ val binary = transaction.toBuffer().readByteArray().toHex()
+
+ // Then
+ assertEquals(fixture(name), legacy.toString(), name)
+ assertCanonicalIdentity(canonical)
+ assertEquals(resource("$name.hex").trim(), binary, name)
+ }
+ }
+
+ private fun assertCanonicalIdentity(element: JsonElement) {
+ if (element is JsonObject) {
+ assertFalse(element.keys.any { it.endsWith("publicKey", ignoreCase = true) })
+ assertFalse(
+ element.keys.any {
+ it == "algorithm" ||
+ it in setOf("representativeAlgorithm", "receiverAlgorithm", "subjectAlgorithm")
+ },
+ )
+ element.values.forEach { assertCanonicalIdentity(it) }
+ }
+ }
+
+ private fun fixture(name: String): String = resource("$name.json")
+
+ private fun resource(name: String): String = checkNotNull(javaClass.getResource("/legacy-http/$name")).readText()
+}
diff --git a/src/test/kotlin/cash/atto/node/account/LegacyHttpFixtures.kt b/src/test/kotlin/cash/atto/node/account/LegacyHttpFixtures.kt
new file mode 100644
index 00000000..8d41352b
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/account/LegacyHttpFixtures.kt
@@ -0,0 +1,61 @@
+package cash.atto.node.account
+
+import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoBlockType
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoReceivable
+import cash.atto.commons.AttoTransaction
+import cash.atto.commons.fromHexToByteArray
+import cash.atto.commons.toAttoVersion
+
+internal object LegacyHttpFixtures {
+ private val address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 }))
+ private val otherAddress = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 2 }))
+ private val hash = AttoHash(ByteArray(32) { 3 })
+ private val timestamp = AttoInstant.fromEpochMilliseconds(1234567890000)
+ private val version = 0U.toAttoVersion()
+
+ val account =
+ AttoAccount(
+ address = address,
+ network = AttoNetwork.LOCAL,
+ version = version,
+ height = AttoHeight(2UL),
+ balance = AttoAmount(10UL),
+ lastTransactionHash = hash,
+ lastTransactionTimestamp = timestamp,
+ representativeAddress = otherAddress,
+ )
+ val entry =
+ AttoAccountEntry(
+ hash = hash,
+ address = address,
+ height = AttoHeight(2UL),
+ blockType = AttoBlockType.SEND,
+ subjectAddress = otherAddress,
+ previousBalance = AttoAmount(13UL),
+ balance = AttoAmount(10UL),
+ timestamp = timestamp,
+ )
+ val receivable =
+ AttoReceivable(
+ network = AttoNetwork.LOCAL,
+ hash = hash,
+ version = version,
+ address = address,
+ timestamp = timestamp,
+ receiverAddress = otherAddress,
+ amount = AttoAmount(3UL),
+ )
+
+ fun transaction(name: String): AttoTransaction =
+ AttoTransaction.fromByteArray(checkNotNull(javaClass.getResource("/legacy-http/$name.hex")).readText().trim().fromHexToByteArray())
+}
diff --git a/src/test/kotlin/cash/atto/node/account/entry/AccountEntryControllerQueryTest.kt b/src/test/kotlin/cash/atto/node/account/entry/AccountEntryQueriesTest.kt
similarity index 90%
rename from src/test/kotlin/cash/atto/node/account/entry/AccountEntryControllerQueryTest.kt
rename to src/test/kotlin/cash/atto/node/account/entry/AccountEntryQueriesTest.kt
index b2f025ca..42c45271 100644
--- a/src/test/kotlin/cash/atto/node/account/entry/AccountEntryControllerQueryTest.kt
+++ b/src/test/kotlin/cash/atto/node/account/entry/AccountEntryQueriesTest.kt
@@ -29,13 +29,13 @@ import org.junit.jupiter.api.Test
import java.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
-class AccountEntryControllerQueryTest {
+class AccountEntryQueriesTest {
private val publicKey = AttoPublicKey(ByteArray(32) { 1 })
private val repository = mockk()
- private val controller = AccountEntryController(repository)
+ private val queries = AccountEntryQueries(repository)
@Test
- fun `hash stream subscribes before lookup and retains a concurrent committed result`() =
+ fun `hash stream subscribes before lookup and retains a concurrent committed result`(): Unit =
runTest {
// Given
val value = sample(2)
@@ -46,7 +46,7 @@ class AccountEntryControllerQueryTest {
finishRead.await()
null
}
- val result = backgroundScope.async { controller.stream(value.hash).first() }
+ val result = backgroundScope.async { queries.stream(value.hash).first() }
// When
runCurrent()
@@ -65,7 +65,7 @@ class AccountEntryControllerQueryTest {
}
@Test
- fun `height stream orders snapshot and overlapping live updates and completes its range`() =
+ fun `height stream orders snapshot and overlapping live updates and completes its range`(): Unit =
runTest {
// Given
val first = sample(2)
@@ -84,7 +84,7 @@ class AccountEntryControllerQueryTest {
val values = mutableListOf()
val collection =
backgroundScope.launch {
- controller.stream(publicKey, 2UL.toAttoHeight(), 4UL.toAttoHeight()).toList(values)
+ queries.stream(publicKey, 2UL.toAttoHeight(), 4UL.toAttoHeight()).toList(values)
}
// When
@@ -108,7 +108,7 @@ class AccountEntryControllerQueryTest {
}
@Test
- fun `cancelling a blocked snapshot cancels the query and releases the live publisher`() =
+ fun `cancelling a blocked snapshot cancels the query and releases the live publisher`(): Unit =
runTest {
// Given
val value = sample(2)
@@ -123,7 +123,7 @@ class AccountEntryControllerQueryTest {
}
val collection =
backgroundScope.launch {
- controller.stream(publicKey, 2UL.toAttoHeight(), 3UL.toAttoHeight()).toList()
+ queries.stream(publicKey, 2UL.toAttoHeight(), 3UL.toAttoHeight()).toList()
}
runCurrent()
val publication = backgroundScope.async { publish(value) }
@@ -140,7 +140,7 @@ class AccountEntryControllerQueryTest {
}
private suspend fun publish(value: AccountEntry) {
- controller.process(AccountEntrySaved(value))
+ queries.process(AccountEntrySaved(value))
}
private fun sample(height: Int): AccountEntry =
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DependencyDiscovererTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DependencyDiscovererTest.kt
index c9755610..698c407e 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DependencyDiscovererTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DependencyDiscovererTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -265,8 +266,7 @@ class DependencyDiscovererTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { marker }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { marker })),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryQueueTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryQueueTest.kt
index 86a21d07..f4333625 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryQueueTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryQueueTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -578,8 +579,7 @@ class DiscoveryQueueTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { marker }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { marker })),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryTestController.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryTestController.kt
index 6112cbc2..e3af0ab4 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryTestController.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/DiscoveryTestController.kt
@@ -1,11 +1,13 @@
package cash.atto.node.bootstrap.discovery
import cash.atto.node.bootstrap.unchecked.UncheckedTransactionProcessor
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
+@Hidden
@RestController
@RequestMapping("/unchecked-transactions/discoveries")
class DiscoveryTestController(
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapDiscovererTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapDiscovererTest.kt
index 41bb816d..48dc0f20 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapDiscovererTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapDiscovererTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -514,7 +515,7 @@ class GapDiscovererTest {
fun response(transaction: AttoTransaction): InboundNetworkMessage {
val request =
- requests.last { it.payload.publicKey == transaction.block.publicKey }
+ requests.last { it.payload.publicKey == transaction.block.address.publicKey }
return InboundNetworkMessage(
source = MessageSource.WEBSOCKET,
publicUri = request.publicUri,
@@ -575,14 +576,12 @@ class GapDiscovererTest {
AttoSendBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
previous = previous,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = publicKey((marker + 20).toByte()),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, publicKey((marker + 20).toByte())),
amount = AttoAmount.MAX,
)
return AttoTransaction(
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapSessionTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapSessionTest.kt
index e835d0b7..846617a3 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapSessionTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/GapSessionTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -290,14 +291,12 @@ class GapSessionTest {
AttoSendBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
previous = previous,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = publicKey((marker + 20).toByte()),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, publicKey((marker + 20).toByte())),
amount = AttoAmount.MAX,
)
return AttoTransaction(
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/LastDiscovererTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/LastDiscovererTest.kt
index 64d3297c..cd02aa54 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/LastDiscovererTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/LastDiscovererTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -228,8 +229,7 @@ class LastDiscovererTest {
val attoVote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { voterMarker }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { voterMarker })),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = transaction.hash,
timestamp = AttoVote.finalTimestamp,
@@ -257,8 +257,7 @@ class LastDiscovererTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { marker }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { marker })),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/discovery/SendDiscovererTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/discovery/SendDiscovererTest.kt
index f7910af7..41c35c54 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/discovery/SendDiscovererTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/discovery/SendDiscovererTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.discovery
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -72,7 +73,7 @@ class SendDiscovererTest {
coEvery { discoveryQueue.queue(any(), DiscoverySource.SEND) } returns true
coEvery {
uncheckedTransactionRepository.hasHigherTransaction(
- missingSend.block.publicKey,
+ missingSend.block.address.publicKey,
missingSend.block.height,
)
} returns 0L
@@ -160,7 +161,7 @@ class SendDiscovererTest {
)
coEvery {
uncheckedTransactionRepository.hasHigherTransaction(
- missingSend.block.publicKey,
+ missingSend.block.address.publicKey,
missingSend.block.height,
)
} returns 1L
@@ -183,7 +184,7 @@ class SendDiscovererTest {
// then
coVerify(exactly = 1) {
uncheckedTransactionRepository.hasHigherTransaction(
- missingSend.block.publicKey,
+ missingSend.block.address.publicKey,
missingSend.block.height,
)
}
@@ -283,14 +284,12 @@ class SendDiscovererTest {
AttoSendBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
previous = AttoHash(ByteArray(32) { (marker + 1).toByte() }),
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = AttoPublicKey(ByteArray(32) { (marker + 2).toByte() }),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { (marker + 2).toByte() })),
amount = AttoAmount.MAX,
)
return AttoTransaction(
@@ -309,8 +308,7 @@ class SendDiscovererTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { marker }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { marker })),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionInserterTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionInserterTest.kt
index ccddb5a0..32078c17 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionInserterTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionInserterTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.unchecked
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -149,14 +150,12 @@ class UncheckedTransactionInserterTest {
AttoOpenBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
sendHashAlgorithm = AttoAlgorithm.V1,
sendHash = AttoHash(ByteArray(32) { 2 }),
- representativeAlgorithm = AttoAlgorithm.V1,
- representativePublicKey = publicKey,
+ representativeAddress = AttoAddress(AttoAlgorithm.V1, publicKey),
),
signature = AttoSignature(ByteArray(64) { 3 }),
work = AttoWork(ByteArray(8) { 4 }),
@@ -169,8 +168,7 @@ class UncheckedTransactionInserterTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { 5 }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 5 })),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionProcessorTest.kt b/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionProcessorTest.kt
index b4ddd475..0887151e 100644
--- a/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionProcessorTest.kt
+++ b/src/test/kotlin/cash/atto/node/bootstrap/unchecked/UncheckedTransactionProcessorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.bootstrap.unchecked
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -233,8 +234,7 @@ class UncheckedTransactionProcessorTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { 1 }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 })),
height = cash.atto.commons.AttoHeight(2UL),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/election/ElectionBootstrapRecoveryTest.kt b/src/test/kotlin/cash/atto/node/election/ElectionBootstrapRecoveryTest.kt
index a29f95f0..05077bf5 100644
--- a/src/test/kotlin/cash/atto/node/election/ElectionBootstrapRecoveryTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/ElectionBootstrapRecoveryTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -408,8 +409,7 @@ class ElectionBootstrapRecoveryTest {
AttoReceiveBlock(
version = account.version,
network = account.network,
- algorithm = account.algorithm,
- publicKey = account.publicKey,
+ address = AttoAddress(account.algorithm, account.publicKey),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(account.balance.raw + 100UL),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
diff --git a/src/test/kotlin/cash/atto/node/election/ElectionProcessorTest.kt b/src/test/kotlin/cash/atto/node/election/ElectionProcessorTest.kt
index ec256afc..d1140e63 100644
--- a/src/test/kotlin/cash/atto/node/election/ElectionProcessorTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/ElectionProcessorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -1067,8 +1068,7 @@ class ElectionProcessorTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height,
balance = AttoAmount.MAX,
timestamp = timestamp,
diff --git a/src/test/kotlin/cash/atto/node/election/ElectionTest.kt b/src/test/kotlin/cash/atto/node/election/ElectionTest.kt
index 431c5bca..9f39ca7d 100644
--- a/src/test/kotlin/cash/atto/node/election/ElectionTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/ElectionTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -345,7 +346,7 @@ class ElectionTest {
publicKey = publicKey,
network = blockA.network,
version = blockA.version,
- algorithm = blockA.algorithm,
+ algorithm = blockA.address.algorithm,
height = 1,
balance = AttoAmount.MIN,
lastTransactionTimestamp = blockA.timestamp.toJavaInstant().minusSeconds(1),
@@ -947,7 +948,7 @@ class ElectionTest {
publicKey = transaction.publicKey,
network = transaction.block.network,
version = transaction.block.version,
- algorithm = transaction.block.algorithm,
+ algorithm = transaction.block.address.algorithm,
height = transaction.height.value.toLong() - 1,
balance = AttoAmount.MIN,
lastTransactionTimestamp =
@@ -971,8 +972,7 @@ class ElectionTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/election/ElectionVoterTest.kt b/src/test/kotlin/cash/atto/node/election/ElectionVoterTest.kt
index ab87f185..63d267a0 100644
--- a/src/test/kotlin/cash/atto/node/election/ElectionVoterTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/ElectionVoterTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -81,7 +82,10 @@ class ElectionVoterTest {
electionVoter.clear()
every { voteWeighter.get() } returns AttoAmount.MAX
every { thisNode.isVoter() } returns true
- every { signer.publicKey } returns AttoPublicKey(Random.nextBytes(ByteArray(32)))
+ val publicKey = AttoPublicKey(Random.nextBytes(ByteArray(32)))
+ every { signer.publicKey } returns publicKey
+ every { thisNode.publicKey } returns publicKey
+ every { thisNode.algorithm } returns AttoAlgorithm.V1
}
@AfterEach
@@ -659,8 +663,7 @@ class ElectionVoterTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = signer.publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, signer.publicKey),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/election/FinalVoteRecorderTest.kt b/src/test/kotlin/cash/atto/node/election/FinalVoteRecorderTest.kt
index 7b9d2ee4..1b509bed 100644
--- a/src/test/kotlin/cash/atto/node/election/FinalVoteRecorderTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/FinalVoteRecorderTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -97,8 +98,7 @@ class FinalVoteRecorderTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(Random.nextBytes(ByteArray(32))),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(ByteArray(32)))),
height = AttoHeight(2UL),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/election/PublicKeyHeightElectionTest.kt b/src/test/kotlin/cash/atto/node/election/PublicKeyHeightElectionTest.kt
index eb6c4f8e..dd678e77 100644
--- a/src/test/kotlin/cash/atto/node/election/PublicKeyHeightElectionTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/PublicKeyHeightElectionTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -152,6 +153,76 @@ internal class PublicKeyHeightElectionTest {
assertEquals(AttoAmount(8u), transactionElection.totalWeight)
}
+ @Test
+ fun `should count a newer vote for the same candidate without starting a stability delay`() {
+ // Given
+ val election = PublicKeyHeightElection(sampleAccount(), minimalConfirmationWeightProvider())
+ val transaction = Transaction.sample()
+ val voter = AttoPublicKey(ByteArray(32) { 23 })
+ val timestamp = Instant.now()
+ election.add(transaction)
+ assertTrue(election.add(vote(voter, transaction.hash, timestamp, AttoAmount(5u))))
+
+ // When
+ assertTrue(election.add(vote(voter, transaction.hash, timestamp.plusSeconds(1), AttoAmount(11u))))
+
+ // Then
+ assertEquals(AttoAmount(11u), election.getConsensus()?.totalWeight)
+ }
+
+ @Test
+ fun `should preserve stability exclusion when a newer vote reaffirms a flipped candidate`() {
+ // Given
+ val election = PublicKeyHeightElection(sampleAccount(), minimalConfirmationWeightProvider())
+ val transactionA = Transaction.sample()
+ val transactionB = Transaction.sample()
+ val flipper = AttoPublicKey(ByteArray(32) { 24 })
+ val stableVoter = AttoPublicKey(ByteArray(32) { 25 })
+ val timestamp = Instant.now()
+ election.add(transactionA)
+ election.add(transactionB)
+ assertTrue(election.add(vote(stableVoter, transactionB.hash, timestamp, AttoAmount(9u))))
+ assertTrue(election.add(vote(flipper, transactionA.hash, timestamp, AttoAmount(3u))))
+ assertTrue(election.add(vote(flipper, transactionB.hash, timestamp.plusSeconds(1), AttoAmount(3u))))
+
+ // When
+ assertTrue(election.add(vote(flipper, transactionB.hash, timestamp.plusSeconds(2), AttoAmount(3u))))
+
+ // Then
+ assertSame(transactionB, election.getProvisionalLeader().transaction)
+ assertEquals(AttoAmount(12u), election.getProvisionalLeader().totalWeight)
+ assertNull(election.getConsensus())
+ assertFalse(election.add(vote(flipper, transactionA.hash, timestamp.plusSeconds(2), AttoAmount(3u))))
+ }
+
+ @Test
+ fun `should keep voter timestamps and stability state detached in a snapshot`() {
+ // Given
+ val election = PublicKeyHeightElection(sampleAccount(), minimalConfirmationWeightProvider())
+ val transactionA = Transaction.sample()
+ val transactionB = Transaction.sample()
+ val voter = AttoPublicKey(ByteArray(32) { 26 })
+ val timestamp = Instant.now()
+ election.add(transactionA)
+ election.add(transactionB)
+ assertTrue(election.add(vote(voter, transactionA.hash, timestamp, AttoAmount(11u))))
+ val stableSnapshot = election.snapshot()
+ assertTrue(election.add(vote(voter, transactionB.hash, timestamp.plusSeconds(1), AttoAmount(11u))))
+ val flippedSnapshot = election.snapshot()
+
+ // When
+ assertTrue(election.add(vote(voter, transactionA.hash, timestamp.plusSeconds(2), AttoAmount(11u))))
+
+ // Then
+ assertSame(transactionA, stableSnapshot.getConsensus()?.transaction)
+ assertSame(transactionB, flippedSnapshot.getProvisionalLeader().transaction)
+ assertNull(flippedSnapshot.getConsensus())
+ assertFalse(flippedSnapshot.add(vote(voter, transactionA.hash, timestamp.plusSeconds(1), AttoAmount(11u))))
+ assertTrue(flippedSnapshot.add(vote(voter, transactionB.hash, timestamp.plusSeconds(2), AttoAmount(11u))))
+ assertNull(flippedSnapshot.getConsensus())
+ assertSame(transactionA, election.getProvisionalLeader().transaction)
+ }
+
@Test
fun `should discard older vote from same voter`() {
// given
@@ -344,8 +415,7 @@ internal class PublicKeyHeightElectionTest {
AttoReceiveBlock(
version = 0u.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = 1u.toAttoHeight(),
balance = AttoAmount(0u),
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/election/VoteTimestampRecorderTest.kt b/src/test/kotlin/cash/atto/node/election/VoteTimestampRecorderTest.kt
index b362501f..7b80e646 100644
--- a/src/test/kotlin/cash/atto/node/election/VoteTimestampRecorderTest.kt
+++ b/src/test/kotlin/cash/atto/node/election/VoteTimestampRecorderTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.election
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -156,8 +157,7 @@ class VoteTimestampRecorderTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(Random.nextBytes(ByteArray(32))),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(ByteArray(32)))),
height = AttoHeight(2UL),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/network/HandshakeProtocolTest.kt b/src/test/kotlin/cash/atto/node/network/HandshakeProtocolTest.kt
new file mode 100644
index 00000000..b7dd296d
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/network/HandshakeProtocolTest.kt
@@ -0,0 +1,222 @@
+package cash.atto.node.network
+
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoChallenge
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPrivateKey
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.AttoSignature
+import cash.atto.commons.AttoSigner
+import cash.atto.commons.toHex
+import cash.atto.commons.toSignerBlocking
+import cash.atto.node.transaction.Transaction
+import cash.atto.protocol.AttoNode
+import cash.atto.protocol.NodeFeature
+import io.mockk.coEvery
+import io.mockk.coVerify
+import io.mockk.every
+import io.mockk.mockk
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.runBlocking
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertNotNull
+import org.junit.jupiter.api.Assertions.assertNull
+import org.junit.jupiter.api.Assertions.assertSame
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Assertions.fail
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.EnumSource
+import java.net.URI
+
+class HandshakeProtocolTest {
+ @Test
+ fun `reciprocal challenge exchange authenticates both nodes once`(): Unit =
+ runBlocking {
+ // Given
+ Fixture().use { fixture ->
+ val request = fixture.counterResponse()
+
+ // When
+ val prepared = fixture.protocol.prepareResponse("peer", request)
+
+ // Then
+ assertNotNull(prepared)
+ val handshake = requireNotNull(prepared)
+ assertEquals(fixture.peerNode.publicUri, handshake.publicUri)
+ assertEquals(fixture.peerNode, handshake.node)
+ assertEquals(fixture.localNode, handshake.response.node)
+
+ // When
+ val authenticated =
+ fixture.peerProtocol.authenticateResponse(
+ "local",
+ fixture.localNode.publicUri,
+ request.counterChallenge,
+ handshake.response,
+ )
+
+ // Then
+ assertEquals(fixture.localNode, authenticated)
+ assertNull(fixture.protocol.prepareResponse("peer", request))
+ assertNull(
+ fixture.peerProtocol.authenticateResponse(
+ "local",
+ fixture.localNode.publicUri,
+ request.counterChallenge,
+ handshake.response,
+ ),
+ )
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(CounterFailure::class)
+ fun `rejected counter response consumes challenge before further authentication`(failure: CounterFailure): Unit =
+ runBlocking {
+ // Given
+ Fixture().use { fixture ->
+ val signer = mockk()
+ val protocol = HandshakeProtocol(fixture.genesisTransaction, fixture.localNode, signer)
+ val valid = fixture.counterResponse()
+ val rejected =
+ when (failure) {
+ CounterFailure.URI -> valid.copy(node = valid.node.copy(publicUri = URI("ws://other.example:8082")))
+ CounterFailure.GENESIS -> valid.copy(genesis = AttoHash(ByteArray(32) { 4 }))
+ CounterFailure.SIGNATURE -> valid.copy(signature = AttoSignature(ByteArray(64)))
+ CounterFailure.PREFIX -> valid.copy(counterChallenge = fixture.challenge(fixture.peerNode.publicUri))
+ }
+
+ // When
+ val result = protocol.prepareResponse("peer", rejected)
+ val replay = protocol.prepareResponse("peer", valid)
+
+ // Then
+ assertNull(result)
+ assertNull(replay)
+ coVerify(exactly = 0) { signer.sign(any(), any()) }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(ResponseFailure::class)
+ fun `rejected callback response consumes counter challenge`(failure: ResponseFailure): Unit =
+ runBlocking {
+ // Given
+ Fixture().use { fixture ->
+ val request = fixture.counterResponse()
+ val prepared = requireNotNull(fixture.protocol.prepareResponse("peer", request))
+ val valid = prepared.response
+ val rejected =
+ when (failure) {
+ ResponseFailure.URI -> valid.copy(node = valid.node.copy(publicUri = URI("ws://other.example:8082")))
+ ResponseFailure.SIGNATURE -> valid.copy(signature = AttoSignature(ByteArray(64)))
+ }
+
+ // When
+ val result =
+ fixture.peerProtocol.authenticateResponse("local", fixture.localNode.publicUri, request.counterChallenge, rejected)
+ val replay =
+ fixture.peerProtocol.authenticateResponse("local", fixture.localNode.publicUri, request.counterChallenge, valid)
+
+ // Then
+ assertNull(result)
+ assertNull(replay)
+ }
+ }
+
+ @Test
+ fun `challenge prefix requires local uri followed by random challenge bytes`() {
+ // Given
+ Fixture().use { fixture ->
+ val localChallenge = fixture.challenge(fixture.localNode.publicUri)
+ val peerChallenge = fixture.challenge(fixture.peerNode.publicUri)
+ val randomOnly = ByteArray(ChallengeStore.CHALLENGE_SIZE).toHex()
+
+ // When
+ val localAccepted = fixture.protocol.isChallengePrefixValid(localChallenge)
+ val peerAccepted = fixture.protocol.isChallengePrefixValid(peerChallenge)
+ val randomAccepted = fixture.protocol.isChallengePrefixValid(randomOnly)
+
+ // Then
+ assertTrue(localAccepted)
+ assertFalse(peerAccepted)
+ assertFalse(randomAccepted)
+ }
+ }
+
+ @Test
+ fun `signing cancellation propagates after challenge consumption`(): Unit =
+ runBlocking {
+ // Given
+ Fixture().use { fixture ->
+ val signer = mockk()
+ val cancelled = CancellationException("Signing cancelled")
+ coEvery { signer.sign(any(), any()) } throws cancelled
+ val protocol = HandshakeProtocol(fixture.genesisTransaction, fixture.localNode, signer)
+ val request = fixture.counterResponse()
+
+ // When
+ val failure =
+ try {
+ protocol.prepareResponse("peer", request)
+ fail("Expected signing cancellation")
+ } catch (exception: CancellationException) {
+ exception
+ }
+
+ // Then
+ assertSame(cancelled, failure)
+ assertNull(protocol.prepareResponse("peer", request))
+ coVerify(exactly = 1) { signer.sign(any(), any()) }
+ }
+ }
+
+ enum class CounterFailure {
+ URI,
+ GENESIS,
+ SIGNATURE,
+ PREFIX,
+ }
+
+ enum class ResponseFailure {
+ URI,
+ SIGNATURE,
+ }
+
+ private class Fixture : AutoCloseable {
+ private val challenges = mutableListOf()
+ private val localSigner = AttoPrivateKey.generate().toSignerBlocking()
+ private val peerSigner = AttoPrivateKey.generate().toSignerBlocking()
+ val genesisTransaction = mockk { every { hash } returns AttoHash(ByteArray(32) { 3 }) }
+ val localNode = node(localSigner.publicKey, URI("ws://local.example:8082"))
+ val peerNode = node(peerSigner.publicKey, URI("ws://peer.example:8082"))
+ val protocol = HandshakeProtocol(genesisTransaction, localNode, localSigner)
+ val peerProtocol = HandshakeProtocol(genesisTransaction, peerNode, peerSigner)
+
+ suspend fun counterResponse(): CounterChallengeResponse =
+ peerProtocol.createCounterResponse(challenge(peerNode.publicUri), challenge(localNode.publicUri), AttoInstant.now())
+
+ fun challenge(publicUri: URI): String = ChallengeStore.generate(publicUri).also(challenges::add)
+
+ override fun close() {
+ challenges.forEach(ChallengeStore::remove)
+ }
+
+ private fun node(
+ publicKey: AttoPublicKey,
+ publicUri: URI,
+ ): AttoNode =
+ AttoNode(
+ network = AttoNetwork.LOCAL,
+ protocolVersion = AttoNode.CURRENT_PROTOCOL_VERSION,
+ algorithm = AttoAlgorithm.V1,
+ publicKey = publicKey,
+ publicUri = publicUri,
+ features = setOf(NodeFeature.VOTING),
+ )
+ }
+}
diff --git a/src/test/kotlin/cash/atto/node/receivable/ReceivableControllerTest.kt b/src/test/kotlin/cash/atto/node/receivable/ReceivableQueriesTest.kt
similarity index 81%
rename from src/test/kotlin/cash/atto/node/receivable/ReceivableControllerTest.kt
rename to src/test/kotlin/cash/atto/node/receivable/ReceivableQueriesTest.kt
index 6a35a5a7..c6d6456c 100644
--- a/src/test/kotlin/cash/atto/node/receivable/ReceivableControllerTest.kt
+++ b/src/test/kotlin/cash/atto/node/receivable/ReceivableQueriesTest.kt
@@ -34,23 +34,23 @@ import org.junit.jupiter.api.Test
import java.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
-class ReceivableControllerTest {
+class ReceivableQueriesTest {
@Test
- fun `subscribes to live events before starting the database query`() =
+ fun `subscribes to live events before starting the database query`(): Unit =
runTest {
// Given
val row = receivable(1, amount = 200UL)
val live = receivable(2)
val repository = mockk()
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
coEvery { repository.findAllDesc(any(), any()) } coAnswers {
- controller.process(ReceivableSaved(live))
+ queries.process(ReceivableSaved(live))
flowOf(row)
}
val received = mutableListOf()
// When
- backgroundScope.launch { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(received) }
+ backgroundScope.launch { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(received) }
runCurrent()
// Then
@@ -58,7 +58,7 @@ class ReceivableControllerTest {
}
@Test
- fun `queues live receivables until the database scan completes`() =
+ fun `queues live receivables until the database scan completes`(): Unit =
runTest {
// Given
val first = receivable(1, amount = 300UL)
@@ -74,14 +74,14 @@ class ReceivableControllerTest {
finishScan.await()
emit(second)
}
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val received = mutableListOf()
- backgroundScope.launch { controller.stream(first.receiverPublicKey, AttoAmount(1UL)).toList(received) }
+ backgroundScope.launch { queries.stream(first.receiverPublicKey, AttoAmount(1UL)).toList(received) }
runCurrent()
assertTrue(scanPaused.isCompleted)
// When
- controller.process(ReceivableSaved(live))
+ queries.process(ReceivableSaved(live))
runCurrent()
// Then
@@ -96,7 +96,7 @@ class ReceivableControllerTest {
}
@Test
- fun `filters queued and delayed database notifications after handing off to live events`() =
+ fun `filters queued and delayed database notifications after handing off to live events`(): Unit =
runTest {
// Given
val queuedOverlap = receivable(1, amount = 300UL)
@@ -111,16 +111,16 @@ class ReceivableControllerTest {
finishScan.await()
emit(delayedOverlap)
}
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val received = mutableListOf()
- backgroundScope.launch { controller.stream(queuedOverlap.receiverPublicKey, AttoAmount(1UL)).toList(received) }
+ backgroundScope.launch { queries.stream(queuedOverlap.receiverPublicKey, AttoAmount(1UL)).toList(received) }
runCurrent()
// When
- controller.process(ReceivableSaved(queuedOverlap))
+ queries.process(ReceivableSaved(queuedOverlap))
finishScan.complete(Unit)
runCurrent()
- controller.process(ReceivableSaved(firstLive))
+ queries.process(ReceivableSaved(firstLive))
runCurrent()
// Then
@@ -128,8 +128,8 @@ class ReceivableControllerTest {
// When
advanceTimeBy(60_000)
- controller.process(ReceivableSaved(delayedOverlap))
- controller.process(ReceivableSaved(secondLive))
+ queries.process(ReceivableSaved(delayedOverlap))
+ queries.process(ReceivableSaved(secondLive))
runCurrent()
// Then
@@ -137,7 +137,7 @@ class ReceivableControllerTest {
}
@Test
- fun `preserves distinct pending receivables and database amount order across senders`() =
+ fun `preserves distinct pending receivables and database amount order across senders`(): Unit =
runTest {
// Given
val largest = receivable(1, amount = 300UL).copy(timestamp = Instant.EPOCH.plusSeconds(3))
@@ -146,24 +146,24 @@ class ReceivableControllerTest {
val rows = listOf(largest, otherSender, olderFromSameSender)
val repository = mockk()
coEvery { repository.findAllDesc(any(), any()) } returns flowOf(*rows.toTypedArray())
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
// When
- val received = controller.stream(largest.receiverPublicKey, AttoAmount(1UL)).take(rows.size).toList()
+ val received = queries.stream(largest.receiverPublicKey, AttoAmount(1UL)).take(rows.size).toList()
// Then
assertEquals(rows.map { it.toAttoReceivable() }, received)
}
@Test
- fun `each collection of the same flow has its own database hashes`() =
+ fun `each collection of the same flow has its own database hashes`(): Unit =
runTest {
// Given
val row = receivable(1)
val repository = mockk()
coEvery { repository.findAllDesc(any(), any()) } returns flowOf(row)
- val controller = ReceivableController(repository)
- val stream = controller.stream(row.receiverPublicKey, AttoAmount(1UL))
+ val queries = ReceivableQueries(repository)
+ val stream = queries.stream(row.receiverPublicKey, AttoAmount(1UL))
val first = mutableListOf()
val second = mutableListOf()
@@ -182,7 +182,7 @@ class ReceivableControllerTest {
}
@Test
- fun `concurrent subscribers receive live events independently when one cancels`() =
+ fun `concurrent subscribers receive live events independently when one cancels`(): Unit =
runTest {
// Given
val row = receivable(1)
@@ -190,19 +190,19 @@ class ReceivableControllerTest {
val laterLive = receivable(3)
val repository = mockk()
coEvery { repository.findAllDesc(any(), any()) } returns flowOf(row)
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val first = mutableListOf()
val second = mutableListOf()
- val firstCollection = backgroundScope.launch { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(first) }
- backgroundScope.launch { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(second) }
+ val firstCollection = backgroundScope.launch { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(first) }
+ backgroundScope.launch { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(second) }
runCurrent()
// When
- controller.process(ReceivableSaved(live))
+ queries.process(ReceivableSaved(live))
runCurrent()
firstCollection.cancel()
runCurrent()
- controller.process(ReceivableSaved(laterLive))
+ queries.process(ReceivableSaved(laterLive))
runCurrent()
// Then
@@ -211,7 +211,7 @@ class ReceivableControllerTest {
}
@Test
- fun `backpressures live publication during a slow scan and preserves every buffered event`() =
+ fun `backpressures live publication during a slow scan and preserves every buffered event`(): Unit =
runTest {
// Given
val row = receivable(1, amount = 300UL)
@@ -223,13 +223,13 @@ class ReceivableControllerTest {
finishScan.await()
emit(row)
}
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val received = mutableListOf()
- backgroundScope.launch { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(received) }
+ backgroundScope.launch { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).toList(received) }
runCurrent()
// When
- val publisher = backgroundScope.launch { live.forEach { controller.process(ReceivableSaved(it)) } }
+ val publisher = backgroundScope.launch { live.forEach { queries.process(ReceivableSaved(it)) } }
runCurrent()
// Then
@@ -246,7 +246,7 @@ class ReceivableControllerTest {
}
@Test
- fun `cancelling an active database scan cancels the query and detaches the live listener`() =
+ fun `cancelling an active database scan cancels the query and detaches the live listener`(): Unit =
runTest {
// Given
val row = receivable(1)
@@ -262,11 +262,11 @@ class ReceivableControllerTest {
scanCancelled.complete(Unit)
}
}
- val controller = ReceivableController(repository)
- val collection = backgroundScope.launch { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).collect() }
+ val queries = ReceivableQueries(repository)
+ val collection = backgroundScope.launch { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).collect() }
runCurrent()
assertTrue(scanStarted.isCompleted)
- val publisher = backgroundScope.launch { (2..257).forEach { controller.process(ReceivableSaved(receivable(it))) } }
+ val publisher = backgroundScope.launch { (2..257).forEach { queries.process(ReceivableSaved(receivable(it))) } }
runCurrent()
assertFalse(publisher.isCompleted)
@@ -280,7 +280,7 @@ class ReceivableControllerTest {
}
@Test
- fun `a database query failure propagates and detaches the live listener`() =
+ fun `a database query failure propagates and detaches the live listener`(): Unit =
runTest {
// Given
val row = receivable(1)
@@ -292,13 +292,13 @@ class ReceivableControllerTest {
failScan.await()
throw failure
}
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val collection =
backgroundScope.async {
- runCatching { controller.stream(row.receiverPublicKey, AttoAmount(1UL)).collect() }
+ runCatching { queries.stream(row.receiverPublicKey, AttoAmount(1UL)).collect() }
}
runCurrent()
- val publisher = backgroundScope.launch { (2..257).forEach { controller.process(ReceivableSaved(receivable(it))) } }
+ val publisher = backgroundScope.launch { (2..257).forEach { queries.process(ReceivableSaved(receivable(it))) } }
runCurrent()
assertFalse(publisher.isCompleted)
@@ -314,7 +314,7 @@ class ReceivableControllerTest {
}
@Test
- fun `filters live events by requested receivers and inclusive minimum amount`() =
+ fun `filters live events by requested receivers and inclusive minimum amount`(): Unit =
runTest {
// Given
val first = receivable(1, amount = 100UL)
@@ -324,13 +324,13 @@ class ReceivableControllerTest {
val search = AccountSearch(listOf(first, second).map { AttoAddress(it.receiverAlgorithm, it.receiverPublicKey) })
val repository = mockk()
coEvery { repository.findAllDesc(any(), any()) } returns emptyFlow()
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val received = mutableListOf()
- backgroundScope.launch { controller.stream(search, AttoAmount(100UL)).toList(received) }
+ backgroundScope.launch { queries.stream(search, AttoAmount(100UL)).toList(received) }
runCurrent()
// When
- listOf(belowMinimum, unrequested, first, second).forEach { controller.process(ReceivableSaved(it)) }
+ listOf(belowMinimum, unrequested, first, second).forEach { queries.process(ReceivableSaved(it)) }
runCurrent()
// Then
@@ -339,18 +339,18 @@ class ReceivableControllerTest {
}
@Test
- fun `delays future timestamps without blocking ready receivables`() =
+ fun `delays future timestamps without blocking ready receivables`(): Unit =
runTest {
// Given
val future = receivable(1, amount = 200UL).copy(timestamp = Instant.now().plusSeconds(60))
val ready = receivable(2)
val repository = mockk()
coEvery { repository.findAllDesc(any(), any()) } returns flowOf(future, ready)
- val controller = ReceivableController(repository)
+ val queries = ReceivableQueries(repository)
val received = mutableListOf()
// When
- backgroundScope.launch { controller.stream(ready.receiverPublicKey, AttoAmount(1UL)).toList(received) }
+ backgroundScope.launch { queries.stream(ready.receiverPublicKey, AttoAmount(1UL)).toList(received) }
runCurrent()
// Then
diff --git a/src/test/kotlin/cash/atto/node/signature/MeteredAttoSignerTest.kt b/src/test/kotlin/cash/atto/node/signature/MeteredAttoSignerTest.kt
index 7e939aa0..ee114a4c 100644
--- a/src/test/kotlin/cash/atto/node/signature/MeteredAttoSignerTest.kt
+++ b/src/test/kotlin/cash/atto/node/signature/MeteredAttoSignerTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.signature
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -188,8 +189,7 @@ class MeteredAttoSignerTest {
private fun AttoVote.Companion.sample(publicKey: AttoPublicKey): AttoVote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = AttoHash(Random.nextBytes(ByteArray(32))),
timestamp = AttoInstant.now(),
@@ -199,8 +199,7 @@ class MeteredAttoSignerTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/signature/SignerTest.kt b/src/test/kotlin/cash/atto/node/signature/SignerTest.kt
index 083270ed..33bda0ca 100644
--- a/src/test/kotlin/cash/atto/node/signature/SignerTest.kt
+++ b/src/test/kotlin/cash/atto/node/signature/SignerTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.signature
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -102,8 +103,7 @@ class SignerTest {
private fun AttoVote.Companion.sample(): AttoVote =
AttoVote(
version = AttoVersion(0U),
- algorithm = AttoAlgorithm.V1,
- publicKey = signer.publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, signer.publicKey),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = AttoHash(Random.nextBytes(ByteArray(32))),
timestamp = AttoInstant.now(),
@@ -113,8 +113,7 @@ class SignerTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = signer.publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, signer.publicKey),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
@@ -128,11 +127,9 @@ class SignerTest {
network = AttoNetwork.LOCAL,
hash = AttoHash(Random.Default.nextBytes(32)),
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(Random.nextBytes(32)),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(32))),
timestamp = AttoInstant.now(),
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = signer.publicKey,
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, signer.publicKey),
amount = 1000UL.toAttoAmount(),
)
diff --git a/src/test/kotlin/cash/atto/node/stream/NodeStreamDispatcherTest.kt b/src/test/kotlin/cash/atto/node/stream/NodeStreamDispatcherTest.kt
new file mode 100644
index 00000000..41225891
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/stream/NodeStreamDispatcherTest.kt
@@ -0,0 +1,246 @@
+package cash.atto.node.stream
+
+import cash.atto.commons.AttoAccount
+import cash.atto.commons.AttoAddress
+import cash.atto.commons.AttoAlgorithm
+import cash.atto.commons.AttoAmount
+import cash.atto.commons.AttoHash
+import cash.atto.commons.AttoHeight
+import cash.atto.commons.AttoInstant
+import cash.atto.commons.AttoNetwork
+import cash.atto.commons.AttoPublicKey
+import cash.atto.commons.node.AccountHeightSearch
+import cash.atto.commons.node.AccountSearch
+import cash.atto.commons.node.AttoStreamMethod
+import cash.atto.commons.node.AttoStreamRequest
+import cash.atto.commons.node.HeightSearch
+import cash.atto.commons.toAttoVersion
+import cash.atto.node.HttpSerializationConfiguration
+import cash.atto.node.account.AccountQueries
+import cash.atto.node.account.entry.AccountEntryQueries
+import cash.atto.node.receivable.ReceivableQueries
+import cash.atto.node.transaction.TransactionQueries
+import io.mockk.coEvery
+import io.mockk.coVerify
+import io.mockk.mockk
+import kotlinx.coroutines.flow.emptyFlow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.toList
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.encodeToJsonElement
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertThrows
+import org.junit.jupiter.api.Test
+import org.springframework.web.server.ResponseStatusException
+import java.net.URLEncoder
+import java.nio.charset.StandardCharsets
+
+class NodeStreamDispatcherTest {
+ private val json: Json = HttpSerializationConfiguration().publicApiJson()
+ private val accounts = mockk()
+ private val receivables = mockk()
+ private val entries = mockk()
+ private val transactions = mockk()
+ private val dispatcher = NodeStreamDispatcher(accounts, receivables, entries, transactions, json)
+ private val address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 }))
+ private val encodedAddress = URLEncoder.encode(address.toString(), StandardCharsets.UTF_8)
+ private val hash = AttoHash(ByteArray(32) { 2 })
+
+ @Test
+ fun `mutable account plan prepares independent address streams without starting them`(): Unit =
+ runTest {
+ // Given
+ val second = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 3 }))
+ coEvery { accounts.stream(any()) } returns emptyFlow()
+ val request = post("/v2/accounts/stream", json.encodeToJsonElement(AccountSearch(setOf(address, second))))
+
+ // When
+ val plan = dispatcher.plan(request, true)
+
+ // Then
+ assertEquals(setOf(address.toString(), second.toString()), plan.members.keys)
+ coVerify(exactly = 0) { accounts.stream(any()) }
+
+ // When
+ plan.members
+ .getValue(address.toString())
+ .stream()
+ .toList()
+
+ // Then
+ coVerify(exactly = 1) { accounts.stream(AccountSearch(setOf(address))) }
+ coVerify(exactly = 0) { accounts.stream(AccountSearch(setOf(second))) }
+ }
+
+ @Test
+ fun `mutable planner validates the complete ranges and excludes publication before starting work`(): Unit =
+ runTest {
+ // Given
+ val second = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 3 }))
+ val invalid = HeightSearch(listOf(AccountHeightSearch(address, AttoHeight(1UL)), AccountHeightSearch(second, AttoHeight(0UL))))
+ val duplicate =
+ HeightSearch(listOf(AccountHeightSearch(address, AttoHeight(1UL)), AccountHeightSearch(address, AttoHeight(2UL))))
+ val requests =
+ listOf(
+ post("/v2/accounts/entries/stream", json.encodeToJsonElement(invalid)),
+ post("/v2/accounts/transactions/stream", json.encodeToJsonElement(duplicate)),
+ post("/v2/transactions", JsonPrimitive("ignored")),
+ )
+
+ // When / Then
+ requests.forEach { request ->
+ val failure = runCatching { dispatcher.plan(request, true) }.exceptionOrNull() as ResponseStatusException
+ assertEquals(400, failure.statusCode.value())
+ }
+ coVerify(exactly = 0) { entries.streamMultiple(any()) }
+ coVerify(exactly = 0) { transactions.streamMultiple(any()) }
+ }
+
+ @Test
+ fun `publication is unavailable through static and mutable WebSocket subscriptions`(): Unit =
+ runTest {
+ // Given
+ val request = post("/v2/transactions", JsonPrimitive("ignored"))
+
+ // When
+ val plan = dispatcher.plan(request, false)
+ val staticFailure =
+ runCatching {
+ plan.members.values
+ .single()
+ .stream()
+ .toList()
+ }.exceptionOrNull()
+ val mutableFailure = runCatching { dispatcher.plan(request, true) }.exceptionOrNull()
+
+ // Then
+ assertEquals(404, (staticFailure as ResponseStatusException).statusCode.value())
+ assertEquals(400, (mutableFailure as ResponseStatusException).statusCode.value())
+ }
+
+ @Test
+ fun `all thirteen read stream operations delegate directly with typed inputs`(): Unit =
+ runTest {
+ // Given
+ val search = AccountSearch(listOf(address))
+ val heights = HeightSearch(listOf(AccountHeightSearch(address, AttoHeight(2UL), AttoHeight(5UL))))
+ coEvery { accounts.stream() } returns emptyFlow()
+ coEvery { accounts.stream(search) } returns emptyFlow()
+ coEvery { accounts.stream(address) } returns emptyFlow()
+ coEvery { receivables.stream(search, AttoAmount(7UL)) } returns emptyFlow()
+ coEvery { receivables.stream(address, AttoAmount(1UL)) } returns emptyFlow()
+ coEvery { entries.stream() } returns emptyFlow()
+ coEvery { entries.stream(hash) } returns emptyFlow()
+ coEvery { entries.streamMultiple(heights) } returns emptyFlow()
+ coEvery { entries.stream(address, AttoHeight(1UL), null) } returns emptyFlow()
+ coEvery { transactions.stream() } returns emptyFlow()
+ coEvery { transactions.stream(hash) } returns emptyFlow()
+ coEvery { transactions.streamMultiple(heights) } returns emptyFlow()
+ coEvery { transactions.stream(address, AttoHeight(2UL), AttoHeight(5UL)) } returns emptyFlow()
+ val operations =
+ listOf(
+ get("/v2/accounts/stream"),
+ post("/v2/accounts/stream", json.encodeToJsonElement(search)),
+ get("/v2/accounts/$encodedAddress/stream"),
+ post("/v2/accounts/receivables/stream?minAmount=7", json.encodeToJsonElement(search)),
+ get("/v2/accounts/$encodedAddress/receivables/stream"),
+ get("/v2/accounts/entries/stream"),
+ get("/v2/accounts/entries/$hash/stream"),
+ post("/v2/accounts/entries/stream", json.encodeToJsonElement(heights)),
+ get("/v2/accounts/$encodedAddress/entries/stream"),
+ get("/v2/transactions/stream"),
+ get("/v2/transactions/$hash/stream"),
+ post("/v2/accounts/transactions/stream", json.encodeToJsonElement(heights)),
+ get("/v2/accounts/$encodedAddress/transactions/stream?fromHeight=2&toHeight=5"),
+ )
+
+ // When
+ operations.forEach { assertEquals(emptyList(), dispatcher.dispatch(it).toList()) }
+
+ // Then
+ coVerify(exactly = 1) { accounts.stream() }
+ coVerify(exactly = 1) { accounts.stream(search) }
+ coVerify(exactly = 1) { accounts.stream(address) }
+ coVerify(exactly = 1) { receivables.stream(search, AttoAmount(7UL)) }
+ coVerify(exactly = 1) { receivables.stream(address, AttoAmount(1UL)) }
+ coVerify(exactly = 1) { entries.stream() }
+ coVerify(exactly = 1) { entries.stream(hash) }
+ coVerify(exactly = 1) { entries.streamMultiple(heights) }
+ coVerify(exactly = 1) { entries.stream(address, AttoHeight(1UL), null) }
+ coVerify(exactly = 1) { transactions.stream() }
+ coVerify(exactly = 1) { transactions.stream(hash) }
+ coVerify(exactly = 1) { transactions.streamMultiple(heights) }
+ coVerify(exactly = 1) { transactions.stream(address, AttoHeight(2UL), AttoHeight(5UL)) }
+ }
+
+ @Test
+ fun `stream uses the exact HTTP data serializer`(): Unit =
+ runTest {
+ // Given
+ val account =
+ AttoAccount(
+ address = address,
+ network = AttoNetwork.LOCAL,
+ version = 0U.toAttoVersion(),
+ height = AttoHeight(1UL),
+ balance = AttoAmount(5UL),
+ lastTransactionHash = hash,
+ lastTransactionTimestamp = AttoInstant.now(),
+ representativeAddress = address,
+ )
+ coEvery { accounts.stream() } returns flowOf(account)
+
+ // When
+ val values = dispatcher.dispatch(get("/v2/accounts/stream")).toList()
+
+ // Then
+ assertEquals(listOf(json.encodeToJsonElement(account)), values)
+ }
+
+ @Test
+ fun `finite endpoints unknown operations invalid inputs and wrong methods are rejected`(): Unit =
+ runTest {
+ // Given
+ val cases =
+ listOf(
+ post("/v2/accounts", JsonPrimitive("ignored")) to 404,
+ get("/v2/accounts/$encodedAddress") to 404,
+ get("/v2/transactions/$hash") to 404,
+ get("/v2/accounts/receivables/stream") to 405,
+ post("/v2/transactions/$hash/stream", null) to 405,
+ get("/v2/accounts/invalid/stream") to 400,
+ get("/v2/accounts/$encodedAddress/receivables/stream?minAmount=invalid") to 400,
+ get("/v2/accounts/$encodedAddress/entries/stream?fromHeight=-1") to 400,
+ post("/v2/transactions?deduplicate=invalid", JsonPrimitive("ignored")) to 404,
+ post("/v2/accounts/stream", null) to 400,
+ post("/v2/accounts/stream", JsonPrimitive("invalid")) to 400,
+ )
+
+ // When / Then
+ cases.forEach { (operation, status) ->
+ val result = runCatching { dispatcher.dispatch(operation) }.exceptionOrNull()
+ assertEquals(status, (result as ResponseStatusException).statusCode.value(), operation.path)
+ }
+ }
+
+ @Test
+ fun `relative target helper rejects a double decoded address`() {
+ // Given
+ val target = "/v2/accounts/${URLEncoder.encode(encodedAddress, StandardCharsets.UTF_8)}/stream"
+
+ // When / Then
+ assertThrows(ResponseStatusException::class.java) {
+ kotlinx.coroutines.runBlocking { dispatcher.dispatch(get(target)) }
+ }
+ }
+
+ private fun get(path: String): AttoStreamRequest = AttoStreamRequest(AttoStreamMethod.GET, path)
+
+ private fun post(
+ path: String,
+ body: JsonElement?,
+ ): AttoStreamRequest = AttoStreamRequest(AttoStreamMethod.POST, path, body)
+}
diff --git a/src/test/kotlin/cash/atto/node/stream/NodeStreamQueryWiringTest.kt b/src/test/kotlin/cash/atto/node/stream/NodeStreamQueryWiringTest.kt
new file mode 100644
index 00000000..dc1745c6
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/stream/NodeStreamQueryWiringTest.kt
@@ -0,0 +1,60 @@
+package cash.atto.node.stream
+
+import cash.atto.commons.node.AttoStreamMethod
+import cash.atto.commons.node.AttoStreamRequest
+import cash.atto.node.HttpSerializationConfiguration
+import cash.atto.node.account.LegacyHttpFixtures
+import cash.atto.node.account.entry.AccountEntryController
+import cash.atto.node.account.entry.AccountEntryQueries
+import cash.atto.node.account.entry.AccountEntryRepository
+import cash.atto.node.account.entry.AccountEntrySaved
+import cash.atto.node.account.entry.toEntity
+import io.mockk.mockk
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.async
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.encodeToJsonElement
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+import org.springframework.context.annotation.AnnotationConfigApplicationContext
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+
+class NodeStreamQueryWiringTest {
+ @Test
+ fun `HTTP and WebSocket reads receive the same event from their shared query owner`(): Unit =
+ runBlocking {
+ // Given
+ AnnotationConfigApplicationContext(TestConfiguration::class.java).use { context ->
+ val queries = context.getBean(AccountEntryQueries::class.java)
+ val controller = context.getBean(AccountEntryController::class.java)
+ val json = HttpSerializationConfiguration().publicApiJson()
+ val dispatcher = NodeStreamDispatcher(mockk(), mockk(), queries, mockk(), json)
+ val entry = LegacyHttpFixtures.entry
+ val http = async(start = CoroutineStart.UNDISPATCHED) { controller.stream().first() }
+ val websocket =
+ async(start = CoroutineStart.UNDISPATCHED) {
+ dispatcher.dispatch(AttoStreamRequest(AttoStreamMethod.GET, "/v2/accounts/entries/stream")).first()
+ }
+
+ // When
+ context.publishEvent(AccountEntrySaved(entry.toEntity()))
+
+ // Then
+ withTimeout(5_000) {
+ assertEquals(entry, http.await())
+ assertEquals(json.encodeToJsonElement(entry), websocket.await())
+ }
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ @Import(AccountEntryQueries::class, AccountEntryController::class)
+ class TestConfiguration {
+ @Bean
+ fun entryRepository(): AccountEntryRepository = mockk()
+ }
+}
diff --git a/src/test/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfigurationTest.kt b/src/test/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfigurationTest.kt
new file mode 100644
index 00000000..55d8ad05
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/stream/NodeStreamWebSocketConfigurationTest.kt
@@ -0,0 +1,163 @@
+package cash.atto.node.stream
+
+import cash.atto.commons.node.AttoStreamCommand
+import cash.atto.commons.node.AttoStreamCommandType
+import cash.atto.commons.node.AttoStreamMethod
+import cash.atto.commons.node.AttoStreamProtocol
+import cash.atto.commons.node.AttoStreamRequest
+import cash.atto.commons.node.AttoStreamResponse
+import cash.atto.commons.node.AttoStreamResponseType
+import cash.atto.node.HttpSerializationConfiguration
+import cash.atto.node.account.AccountController
+import cash.atto.node.account.AccountQueries
+import cash.atto.node.account.entry.AccountEntryQueries
+import cash.atto.node.receivable.ReceivableQueries
+import cash.atto.node.transaction.TransactionQueries
+import io.mockk.coEvery
+import io.mockk.mockk
+import kotlinx.coroutines.flow.emptyFlow
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Timeout
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.ValueSource
+import org.springframework.context.annotation.AnnotationConfigApplicationContext
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter
+import org.springframework.web.reactive.config.EnableWebFlux
+import org.springframework.web.server.adapter.WebHttpHandlerBuilder
+import reactor.netty.http.server.HttpServer
+import java.net.URI
+import java.net.http.HttpClient
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+import java.net.http.WebSocket
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.CompletionStage
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.TimeUnit
+
+@Timeout(15)
+class NodeStreamWebSocketConfigurationTest {
+ @ParameterizedTest
+ @ValueSource(booleans = [false, true])
+ fun `actual Node configuration serves read streams and rejects WebSocket publication`(publication: Boolean) {
+ // Given
+ AnnotationConfigApplicationContext(TestConfiguration::class.java).use { context ->
+ val adapter = ReactorHttpHandlerAdapter(WebHttpHandlerBuilder.applicationContext(context).build())
+ val server =
+ HttpServer
+ .create()
+ .host("127.0.0.1")
+ .port(0)
+ .handle(adapter)
+ .bindNow()
+ try {
+ HttpClient.newHttpClient().use { client ->
+ val responses = CopyOnWriteArrayList()
+ val closed = CompletableFuture()
+ val listener =
+ object : WebSocket.Listener {
+ private val text = StringBuilder()
+
+ override fun onOpen(webSocket: WebSocket) {
+ webSocket.request(1)
+ }
+
+ override fun onText(
+ webSocket: WebSocket,
+ data: CharSequence,
+ last: Boolean,
+ ): CompletionStage<*>? {
+ text.append(data)
+ if (last) {
+ responses.add(AttoStreamProtocol.decodeResponse(text.toString()))
+ text.setLength(0)
+ }
+ webSocket.request(1)
+ return null
+ }
+
+ override fun onClose(
+ webSocket: WebSocket,
+ statusCode: Int,
+ reason: String,
+ ): CompletionStage<*>? {
+ closed.complete(Unit)
+ return null
+ }
+
+ override fun onError(
+ webSocket: WebSocket,
+ error: Throwable,
+ ) {
+ closed.completeExceptionally(error)
+ }
+ }
+
+ // When
+ val http =
+ client.send(
+ HttpRequest.newBuilder(URI("http://127.0.0.1:${server.port()}/v2/accounts/stream")).GET().build(),
+ HttpResponse.BodyHandlers.ofString(),
+ )
+ val socket = client.newWebSocketBuilder().buildAsync(URI("ws://127.0.0.1:${server.port()}/v2/stream"), listener).join()
+ try {
+ socket
+ .sendText(
+ AttoStreamProtocol.encodeCommand(
+ AttoStreamCommand(
+ AttoStreamCommandType.SUBSCRIBE,
+ AttoStreamRequest(
+ if (publication) AttoStreamMethod.POST else AttoStreamMethod.GET,
+ if (publication) "/v2/transactions" else "/v2/accounts/stream",
+ ),
+ ),
+ ),
+ true,
+ ).join()
+ closed.get(5, TimeUnit.SECONDS)
+
+ // Then
+ assertEquals(200, http.statusCode())
+ assertEquals("", http.body())
+ val expected =
+ listOf(
+ AttoStreamResponseType.SUBSCRIBED,
+ if (publication) AttoStreamResponseType.ERROR else AttoStreamResponseType.COMPLETE,
+ )
+ assertEquals(expected, responses.map { it.type }.filter { it != AttoStreamResponseType.HEARTBEAT })
+ if (publication) assertEquals(404, responses.last().status)
+ } finally {
+ socket.abort()
+ }
+ }
+ } finally {
+ server.disposeNow()
+ }
+ }
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ @EnableWebFlux
+ @Import(
+ HttpSerializationConfiguration::class,
+ NodeStreamWebSocketConfiguration::class,
+ NodeStreamDispatcher::class,
+ AccountController::class,
+ )
+ private class TestConfiguration {
+ @Bean
+ fun accounts(): AccountQueries = mockk().also { coEvery { it.stream() } returns emptyFlow() }
+
+ @Bean
+ fun entries(): AccountEntryQueries = mockk()
+
+ @Bean
+ fun receivables(): ReceivableQueries = mockk()
+
+ @Bean
+ fun transactions(): TransactionQueries = mockk()
+ }
+}
diff --git a/src/test/kotlin/cash/atto/node/transaction/LegacyTransactionRequestTest.kt b/src/test/kotlin/cash/atto/node/transaction/LegacyTransactionRequestTest.kt
new file mode 100644
index 00000000..8c6b2b9e
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/transaction/LegacyTransactionRequestTest.kt
@@ -0,0 +1,104 @@
+package cash.atto.node.transaction
+
+import cash.atto.node.account.LegacyHttpFixtures
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.encodeToJsonElement
+import kotlinx.serialization.json.jsonObject
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertThrows
+import org.junit.jupiter.api.Test
+
+class LegacyTransactionRequestTest {
+ private val json = Json { ignoreUnknownKeys = true }
+ private val blockNames = listOf("open", "receive", "send", "change")
+
+ @Test
+ fun `legacy key-only blocks decode through the local request boundary with implicit open height`() {
+ // Given
+ for (name in blockNames) {
+ val expected = LegacyHttpFixtures.transaction(name)
+ val payload =
+ fixture(name).withBlock { block ->
+ JsonObject(
+ block.filterKeys {
+ it !in setOf("address", "receiverAddress", "representativeAddress") &&
+ (name != "open" || it != "height")
+ },
+ )
+ }
+
+ // When
+ val request = json.decodeFromString(payload.toString())
+ val encoded = json.encodeToJsonElement(request)
+
+ // Then
+ assertEquals(expected, request.transaction, name)
+ assertEquals(json.encodeToJsonElement(expected), encoded, name)
+ assertEquals(setOf("block", "signature", "work"), encoded.jsonObject.keys)
+ }
+ }
+
+ @Test
+ fun `canonical addresses take priority without parsing malformed duplicate legacy identities`() {
+ // Given
+ for (name in blockNames) {
+ val payload =
+ fixture(name).withBlock { block ->
+ JsonObject(
+ block.mapValues { (key, value) ->
+ when {
+ key == "algorithm" || key.endsWith("Algorithm") && key != "sendHashAlgorithm" -> JsonObject(emptyMap())
+ key.endsWith("PublicKey") || key == "publicKey" -> JsonArray(listOf(JsonNull))
+ else -> value
+ }
+ },
+ )
+ }
+
+ // When
+ val request = json.decodeFromString(payload.toString())
+
+ // Then
+ assertEquals(LegacyHttpFixtures.transaction(name), request.transaction, name)
+ }
+ }
+
+ @Test
+ fun `present null canonical address is rejected instead of falling back to a legacy key`() {
+ // Given
+ val payload = fixture("send").withBlock { block -> JsonObject(block + ("address" to JsonNull)) }
+
+ // When / Then
+ assertThrows(SerializationException::class.java) { json.decodeFromString(payload.toString()) }
+ }
+
+ @Test
+ fun `missing legacy identity pairs are rejected at the request boundary`() {
+ // Given
+ val payload = fixture("send").withBlock { block -> JsonObject(block - setOf("address", "publicKey")) }
+
+ // When / Then
+ assertThrows(SerializationException::class.java) { json.decodeFromString(payload.toString()) }
+ }
+
+ @Test
+ fun `request normalization retains the caller unknown field policy`() {
+ // Given
+ val strictJson = Json { ignoreUnknownKeys = false }
+ val payload = fixture("send").withBlock { block -> JsonObject(block + ("future" to JsonPrimitive(true))) }
+
+ // When / Then
+ assertThrows(SerializationException::class.java) { strictJson.decodeFromString(payload.toString()) }
+ }
+
+ private fun fixture(name: String): JsonObject =
+ Json.parseToJsonElement(checkNotNull(javaClass.getResource("/legacy-http/$name.json")).readText()).jsonObject
+
+ private fun JsonObject.withBlock(transform: (JsonObject) -> JsonObject): JsonObject =
+ JsonObject(this + ("block" to transform(getValue("block").jsonObject)))
+}
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionControllerElectionRejectionTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionControllerElectionRejectionTest.kt
index 5939af2c..fa098623 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionControllerElectionRejectionTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionControllerElectionRejectionTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -220,14 +221,12 @@ internal class TransactionControllerElectionRejectionTest {
AttoSendBlock(
version = account.version,
network = account.network,
- algorithm = account.algorithm,
- publicKey = account.publicKey,
+ address = AttoAddress(account.algorithm, account.publicKey),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(account.balance.raw - 10UL),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = AttoPublicKey(Random.nextBytes(32)),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(32))),
amount = AttoAmount(10UL),
)
return Transaction(block, privateKey.sign(block.hash), AttoWorker.cpu().work(block))
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionMetricProviderTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionMetricProviderTest.kt
index 5a62683e..66b3122c 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionMetricProviderTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionMetricProviderTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -68,8 +69,7 @@ class TransactionMetricProviderTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32)),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32))),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionNetworkProviderTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionNetworkProviderTest.kt
index ec926daf..2d26c1c4 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionNetworkProviderTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionNetworkProviderTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -276,14 +277,12 @@ class TransactionNetworkProviderTest {
AttoSendBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
previous = previous,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = publicKey(102),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, publicKey(102)),
amount = AttoAmount.MAX,
)
return Transaction(
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionPublicationControllerTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionPublicationControllerTest.kt
index aebb3120..3daab4ab 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionPublicationControllerTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionPublicationControllerTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -17,6 +18,7 @@ import cash.atto.node.ApplicationProperties
import cash.atto.node.account.Account
import cash.atto.node.account.AccountUpdated
import cash.atto.node.election.ElectionRejected
+import cash.atto.node.network.InboundNetworkMessage
import cash.atto.node.network.NetworkMessagePublisher
import cash.atto.protocol.AttoNode
import cash.atto.protocol.NodeFeature
@@ -27,10 +29,14 @@ import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.jupiter.api.Assertions.assertEquals
@@ -54,8 +60,7 @@ internal class TransactionPublicationControllerTest {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight(2UL),
balance = AttoAmount(1UL),
timestamp = AttoInstant.now(),
@@ -71,10 +76,10 @@ internal class TransactionPublicationControllerTest {
)
private val account =
Account(
- publicKey = block.publicKey,
+ publicKey = block.address.publicKey,
network = block.network,
version = block.version,
- algorithm = block.algorithm,
+ algorithm = block.address.algorithm,
height = block.height.value.toLong(),
balance = block.balance,
lastTransactionTimestamp = block.timestamp.toJavaInstant(),
@@ -92,6 +97,72 @@ internal class TransactionPublicationControllerTest {
features = setOf(NodeFeature.VOTING, NodeFeature.HISTORICAL),
)
+ @Test
+ fun `HTTP publication uses the configured proxy header and remote port`(): Unit =
+ runTest {
+ // Given
+ val properties = ApplicationProperties().apply { useXForwardedFor = true }
+ val publisher = mockk(relaxed = true)
+ val repository = mockk()
+ val controller = TransactionPublicationController(properties, node, publisher, repository)
+ val request =
+ MockServerHttpRequest
+ .post("/v2/transactions")
+ .remoteAddress(InetSocketAddress("127.0.0.1", 12345))
+ .header("X-Forwarded-For", "203.0.113.10")
+ .build()
+ val result =
+ async(start = CoroutineStart.UNDISPATCHED) {
+ controller.publishAndStream(transaction.toAttoTransaction(), request, false).first()
+ }
+
+ // When
+ controller.process(AccountUpdated(TransactionSource.ELECTION, account, account, transaction))
+
+ // Then
+ assertEquals(transaction.toAttoTransaction(), result.await())
+ verify(exactly = 1) {
+ publisher.publish(
+ match> {
+ it.socketAddress.hostString == "203.0.113.10" && it.socketAddress.port == 12345
+ },
+ )
+ }
+ }
+
+ @Test
+ @OptIn(ExperimentalCoroutinesApi::class)
+ fun `HTTP publication keeps the forty second confirmation deadline`(): Unit =
+ runTest {
+ // Given
+ val publisher = mockk(relaxed = true)
+ val controller = TransactionPublicationController(ApplicationProperties(), node, publisher, mockk())
+ val request =
+ MockServerHttpRequest
+ .post("/v2/transactions")
+ .remoteAddress(InetSocketAddress("127.0.0.1", 12345))
+ .build()
+ val result =
+ async(start = CoroutineStart.UNDISPATCHED) {
+ runCatching { controller.publishAndStream(transaction.toAttoTransaction(), request, false).first() }
+ }
+
+ // When
+ advanceTimeBy(39_999)
+ runCurrent()
+
+ // Then
+ assertFalse(result.isCompleted)
+
+ // When
+ advanceTimeBy(1)
+ runCurrent()
+
+ // Then
+ assertInstanceOf(TimeoutCancellationException::class.java, result.await().exceptionOrNull())
+ verify(exactly = 1) { publisher.publish(any()) }
+ }
+
@ParameterizedTest
@ValueSource(booleans = [false, true])
fun `election rejection resolves publication and stream waiters according to stored hash`(confirmed: Boolean) =
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionControllerQueryTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionQueriesTest.kt
similarity index 88%
rename from src/test/kotlin/cash/atto/node/transaction/TransactionControllerQueryTest.kt
rename to src/test/kotlin/cash/atto/node/transaction/TransactionQueriesTest.kt
index aa2e65db..2045936c 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionControllerQueryTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionQueriesTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -35,13 +36,13 @@ import org.junit.jupiter.api.Test
import java.time.Instant
@OptIn(ExperimentalCoroutinesApi::class)
-class TransactionControllerQueryTest {
+class TransactionQueriesTest {
private val publicKey = AttoPublicKey(ByteArray(32) { 1 })
private val repository = mockk()
- private val controller = TransactionController(repository)
+ private val queries = TransactionQueries(repository)
@Test
- fun `hash stream subscribes before lookup and retains a concurrent committed result`() =
+ fun `hash stream subscribes before lookup and retains a concurrent committed result`(): Unit =
runTest {
// Given
val value = sample(2)
@@ -52,7 +53,7 @@ class TransactionControllerQueryTest {
finishRead.await()
null
}
- val result = backgroundScope.async { controller.stream(value.hash).first() }
+ val result = backgroundScope.async { queries.stream(value.hash).first() }
// When
runCurrent()
@@ -71,7 +72,7 @@ class TransactionControllerQueryTest {
}
@Test
- fun `height stream orders snapshot and overlapping live updates and completes its range`() =
+ fun `height stream orders snapshot and overlapping live updates and completes its range`(): Unit =
runTest {
// Given
val first = sample(2)
@@ -90,7 +91,7 @@ class TransactionControllerQueryTest {
val values = mutableListOf()
val collection =
backgroundScope.launch {
- controller.stream(publicKey, 2UL.toAttoHeight(), 4UL.toAttoHeight()).toList(values)
+ queries.stream(publicKey, 2UL.toAttoHeight(), 4UL.toAttoHeight()).toList(values)
}
// When
@@ -114,7 +115,7 @@ class TransactionControllerQueryTest {
}
@Test
- fun `cancelling a blocked snapshot cancels the query and releases the live publisher`() =
+ fun `cancelling a blocked snapshot cancels the query and releases the live publisher`(): Unit =
runTest {
// Given
val value = sample(2)
@@ -129,7 +130,7 @@ class TransactionControllerQueryTest {
}
val collection =
backgroundScope.launch {
- controller.stream(publicKey, 2UL.toAttoHeight(), 3UL.toAttoHeight()).toList()
+ queries.stream(publicKey, 2UL.toAttoHeight(), 3UL.toAttoHeight()).toList()
}
runCurrent()
val publication = backgroundScope.async { publish(value) }
@@ -146,7 +147,7 @@ class TransactionControllerQueryTest {
}
private suspend fun publish(value: Transaction) {
- controller.process(AccountUpdated(TransactionSource.BOOTSTRAP, mockk(), mockk(), value))
+ queries.process(AccountUpdated(TransactionSource.BOOTSTRAP, mockk(), mockk(), value))
}
private fun sample(
@@ -157,8 +158,7 @@ class TransactionControllerQueryTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, publicKey),
height = height.toULong().toAttoHeight(),
balance = AttoAmount(height.toULong()),
timestamp = Instant.EPOCH.plusSeconds(height.toLong()).toAtto(),
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionQueueTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionQueueTest.kt
index b985e046..2c0b2eb6 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionQueueTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionQueueTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -259,8 +260,7 @@ internal class TransactionQueueTest {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(Random.nextBytes(ByteArray(32))),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(ByteArray(32)))),
height = 2U.toAttoHeight(),
balance = AttoAmount(amount),
timestamp = timestamp.toAtto(),
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionRebroadcasterTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionRebroadcasterTest.kt
index 0cc5af53..8d6c499e 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionRebroadcasterTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionRebroadcasterTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -116,8 +117,7 @@ internal class TransactionRebroadcasterTest {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(Random.nextBytes(ByteArray(32))),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(Random.nextBytes(ByteArray(32)))),
height = 2U.toAttoHeight(),
balance = AttoAmount(100u),
timestamp = Instant.now().toAtto(),
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinition.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinition.kt
index bd5e65a8..3292f1a5 100644
--- a/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinition.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinition.kt
@@ -2,6 +2,7 @@ package cash.atto.node.transaction
import cash.atto.commons.AttoAccount
import cash.atto.commons.AttoAccountEntry
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -15,10 +16,14 @@ import cash.atto.node.Neighbour
import cash.atto.node.PropertyHolder
import cash.atto.node.Waiter
import cash.atto.node.Waiter.waitUntilNonNull
+import cash.atto.node.account.LegacyAccountResponse
+import cash.atto.node.account.entry.LegacyAccountEntryResponse
+import cash.atto.node.receivable.LegacyReceivableResponse
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.Json
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToFlux
@@ -48,7 +53,7 @@ class TransactionStepDefinition(
val receiverPublicKeyAlgorithm = PropertyHolder[AttoAlgorithm::class.java, receiverShortId]
val receiverPublicKey = PropertyHolder[AttoPublicKey::class.java, receiverShortId]
- val send = account.send(receiverPublicKeyAlgorithm, receiverPublicKey, defaultSendAmount)
+ val send = account.send(AttoAddress(receiverPublicKeyAlgorithm, receiverPublicKey), defaultSendAmount)
val sendBlock = send.first
val sendTransaction =
Transaction(
@@ -88,7 +93,7 @@ class TransactionStepDefinition(
)
} else {
val open =
- AttoAccount.open(receivable.receiverAlgorithm, receivable.receiverPublicKey, receivable)
+ AttoAccount.open(receivable.receiverAddress, receivable)
val openBlock = open.first
Transaction(
block = openBlock,
@@ -116,7 +121,7 @@ class TransactionStepDefinition(
val representativePublicKey = PropertyHolder.get(AttoPublicKey::class.java, representativeShortId)
- val change = account.change(AttoAlgorithm.V1, representativePublicKey)
+ val change = account.change(AttoAddress(AttoAlgorithm.V1, representativePublicKey))
val changeBlock = change.first
val changeTransaction =
Transaction(
@@ -148,31 +153,61 @@ class TransactionStepDefinition(
streamTransaction(PropertyHolder[Neighbour::class.java, shortId], expectedTransaction.hash)
}
- private fun getAccount(
+ internal fun getAccount(
neighbour: Neighbour,
publicKey: AttoPublicKey,
- ): AttoAccount? =
- webClient
- .get()
- .uri("http://localhost:${neighbour.httpPort}/accounts/{publicKey}", publicKey.toString())
- .retrieve()
- .onStatus({ it.value() == 404 }, { Mono.empty() })
- .bodyToMono()
- .blockOptional()
- .orElse(null)
-
- private fun streamTransaction(
+ ): AttoAccount? {
+ val response =
+ webClient
+ .get()
+ .uri(
+ "http://localhost:${neighbour.httpPort}" + if (neighbour.released) "/accounts/{account}" else "/v2/accounts/{account}",
+ accountIdentifier(neighbour, publicKey),
+ ).retrieve()
+ .onStatus({ it.value() == 404 }, { Mono.empty() })
+ return if (neighbour.released) {
+ response.bodyToMono().map {
+ AttoAccount(
+ address = AttoAddress(it.algorithm, it.publicKey),
+ network = it.network,
+ version = it.version,
+ height = it.height,
+ balance = it.balance,
+ lastTransactionHash = it.lastTransactionHash,
+ lastTransactionTimestamp = it.lastTransactionTimestamp,
+ representativeAddress = AttoAddress(it.representativeAlgorithm, it.representativePublicKey),
+ )
+ }
+ } else {
+ response.bodyToMono()
+ }.blockOptional().orElse(null)
+ }
+
+ internal fun streamTransaction(
neighbour: Neighbour,
hash: AttoHash,
): AttoTransaction {
try {
return waitUntilNonNull {
- webClient
- .get()
- .uri("http://localhost:${neighbour.httpPort}/transactions/{hash}/stream", hash.toString())
- .retrieve()
- .onStatus({ it.value() == 404 }, { Mono.empty() })
- .bodyToMono()
+ val response =
+ webClient
+ .get()
+ .uri(
+ "http://localhost:${neighbour.httpPort}${if (neighbour.released) "" else "/v2"}/transactions/{hash}/stream",
+ hash.toString(),
+ ).retrieve()
+ .onStatus({ it.value() == 404 }, { Mono.empty() })
+ val transaction =
+ if (neighbour.released) {
+ response.bodyToMono().map { it.transaction }
+ } else {
+ response
+ .bodyToFlux()
+ .filter { it.isNotBlank() }
+ .map { Json.decodeFromString(it) }
+ .single()
+ }
+ transaction
.timeout(Duration.ofSeconds(1))
.onErrorResume(TimeoutException::class.java) { Mono.empty() }
.doOnSubscribe { logger.info { "Started streaming transaction $hash" } }
@@ -185,20 +220,39 @@ class TransactionStepDefinition(
}
}
- private fun streamAccountEntries(
+ internal fun streamAccountEntries(
neighbour: Neighbour,
publicKey: AttoPublicKey,
hash: AttoHash,
height: AttoHeight,
): AttoAccountEntry {
- val url = "http://localhost:${neighbour.httpPort}/accounts/$publicKey/entries/stream?fromHeight=$height&toHeight=$height"
+ val prefix = if (neighbour.released) "" else "/v2"
+ val url = "http://localhost:${neighbour.httpPort}$prefix/accounts/{account}/entries/stream?fromHeight=$height&toHeight=$height"
try {
- return webClient
- .get()
- .uri(url)
- .retrieve()
- .onStatus({ it.value() == 404 }, { Mono.empty() })
- .bodyToFlux()
+ val response =
+ webClient
+ .get()
+ .uri(url, accountIdentifier(neighbour, publicKey))
+ .retrieve()
+ .onStatus({ it.value() == 404 }, { Mono.empty() })
+ val entries =
+ if (neighbour.released) {
+ response.bodyToFlux().map {
+ AttoAccountEntry(
+ hash = it.hash,
+ address = it.address,
+ height = it.height,
+ blockType = it.blockType,
+ subjectAddress = it.subjectAddress,
+ previousBalance = it.previousBalance,
+ balance = it.balance,
+ timestamp = it.timestamp,
+ )
+ }
+ } else {
+ response.bodyToFlux().filter { it.isNotBlank() }.map { Json.decodeFromString(it) }
+ }
+ return entries
.filter { it.hash == hash }
.blockFirst(Duration.ofSeconds(Waiter.timeoutInSeconds))!!
} catch (e: Exception) {
@@ -206,32 +260,73 @@ class TransactionStepDefinition(
}
}
- private fun streamReceivable(
+ internal fun streamReceivable(
neighbour: Neighbour,
publicKey: AttoPublicKey,
sendHash: AttoHash,
- ): AttoReceivable =
- webClient
- .get()
- .uri("http://localhost:${neighbour.httpPort}/accounts/{publicKey}/receivables/stream", publicKey.toString())
- .retrieve()
- .onStatus({ it.value() == 404 }, { Mono.empty() })
- .bodyToFlux()
+ ): AttoReceivable {
+ val prefix = if (neighbour.released) "" else "/v2"
+ val response =
+ webClient
+ .get()
+ .uri(
+ "http://localhost:${neighbour.httpPort}$prefix/accounts/{account}/receivables/stream",
+ accountIdentifier(neighbour, publicKey),
+ ).retrieve()
+ .onStatus({ it.value() == 404 }, { Mono.empty() })
+ val receivables =
+ if (neighbour.released) {
+ response.bodyToFlux().map {
+ AttoReceivable(
+ network = it.network,
+ hash = it.hash,
+ version = it.version,
+ address = AttoAddress(it.algorithm, it.publicKey),
+ timestamp = it.timestamp,
+ receiverAddress = AttoAddress(it.receiverAlgorithm, it.receiverPublicKey),
+ amount = it.amount,
+ )
+ }
+ } else {
+ response.bodyToFlux().filter { it.isNotBlank() }.map { Json.decodeFromString(it) }
+ }
+ return receivables
.filter { it.hash == sendHash }
.blockFirst(Duration.ofSeconds(Waiter.timeoutInSeconds))!!
+ }
+
+ private fun accountIdentifier(
+ neighbour: Neighbour,
+ publicKey: AttoPublicKey,
+ ): String = if (neighbour.released) publicKey.toString() else AttoAddress(AttoAlgorithm.V1, publicKey).toString()
private fun publish(
neighbourShortId: String,
transaction: Transaction,
+ ) = publish(PropertyHolder[Neighbour::class.java, neighbourShortId], transaction)
+
+ internal fun publish(
+ neighbour: Neighbour,
+ transaction: Transaction,
) {
- val neighbour = PropertyHolder[Neighbour::class.java, neighbourShortId]
- webClient
- .post()
- .uri("http://localhost:${neighbour.httpPort}/transactions")
- .contentType(MediaType.APPLICATION_JSON)
- .bodyValue(transaction.toAttoTransaction())
- .retrieve()
- .bodyToMono()
- .block()
+ val canonical = transaction.toAttoTransaction()
+ val response =
+ webClient
+ .post()
+ .uri("http://localhost:${neighbour.httpPort}${if (neighbour.released) "" else "/v2"}/transactions")
+ .contentType(MediaType.APPLICATION_JSON)
+ .bodyValue(if (neighbour.released) canonical.toLegacyResponse() else canonical)
+ .retrieve()
+ val confirmed =
+ if (neighbour.released) {
+ response.bodyToMono().map { it.transaction }
+ } else {
+ response
+ .bodyToFlux()
+ .filter { it.isNotBlank() }
+ .map { Json.decodeFromString(it) }
+ .single()
+ }.block()
+ check(confirmed?.hash == transaction.hash) { "Publication did not confirm ${transaction.hash} (neighbour=$neighbour)" }
}
}
diff --git a/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinitionHttpTest.kt b/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinitionHttpTest.kt
new file mode 100644
index 00000000..dcb916e7
--- /dev/null
+++ b/src/test/kotlin/cash/atto/node/transaction/TransactionStepDefinitionHttpTest.kt
@@ -0,0 +1,190 @@
+package cash.atto.node.transaction
+
+import cash.atto.commons.AttoHeight
+import cash.atto.node.ApplicationTestConfiguration
+import cash.atto.node.Neighbour
+import cash.atto.node.account.LegacyHttpFixtures
+import kotlinx.serialization.SerializationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertThrows
+import org.junit.jupiter.api.Test
+import reactor.core.publisher.Mono
+import reactor.netty.http.server.HttpServer
+import java.net.URLEncoder
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.CopyOnWriteArrayList
+
+class TransactionStepDefinitionHttpTest {
+ @Test
+ fun `released neighbours use legacy paths and frozen JSON for reads and all publication block types`(): Unit =
+ verifyHttpBoundary(released = true)
+
+ @Test
+ fun `classpath neighbours use encoded v2 paths and ignore blank heartbeats before and after records`(): Unit =
+ verifyHttpBoundary(released = false)
+
+ @Test
+ fun `publication requires the response to confirm the submitted hash`() {
+ // Given
+ val submitted = LegacyHttpFixtures.transaction("send").toTransaction()
+ val other = LegacyHttpFixtures.transaction("change")
+ val server =
+ HttpServer
+ .create()
+ .host("127.0.0.1")
+ .port(0)
+ .handle { _, response ->
+ response.header("Content-Type", "application/x-ndjson").sendString(Mono.just(Json.encodeToString(other) + "\n"))
+ }.bindNow()
+ try {
+ val steps = TransactionStepDefinition(ApplicationTestConfiguration().webClient(false))
+ // When
+ val failure =
+ assertThrows(IllegalStateException::class.java) {
+ steps.publish(Neighbour(0U, server.port().toUShort()), submitted)
+ }
+ // Then
+ assertEquals(
+ "Publication did not confirm ${submitted.hash} (neighbour=${Neighbour(0U, server.port().toUShort())})",
+ failure.message,
+ )
+ } finally {
+ server.disposeNow()
+ }
+ }
+
+ @Test
+ fun `v2 streaming still rejects malformed nonblank records`() {
+ // Given
+ val server =
+ HttpServer
+ .create()
+ .host("127.0.0.1")
+ .port(0)
+ .handle { _, response ->
+ response.header("Content-Type", "application/x-ndjson").sendString(Mono.just("\n \t\nnot-json\n"))
+ }.bindNow()
+ try {
+ val steps = TransactionStepDefinition(ApplicationTestConfiguration().webClient(false))
+ // When / Then
+ assertThrows(SerializationException::class.java) {
+ steps.streamReceivable(
+ Neighbour(0U, server.port().toUShort()),
+ LegacyHttpFixtures.account.address.publicKey,
+ LegacyHttpFixtures.receivable.hash,
+ )
+ }
+ } finally {
+ server.disposeNow()
+ }
+ }
+
+ private fun verifyHttpBoundary(released: Boolean) {
+ // Given
+ val requests = CopyOnWriteArrayList>()
+ val publicationBodies = CopyOnWriteArrayList()
+ val server =
+ HttpServer
+ .create()
+ .host("127.0.0.1")
+ .port(0)
+ .handle { request, response ->
+ requests.add(request.method().name() to request.uri())
+ val path = request.path()
+ if (request.method().name() == "POST") {
+ request.receive().aggregate().asString().flatMap { body ->
+ publicationBodies.add(Json.parseToJsonElement(body))
+ val output = if (released) body else "\n \t\n$body\n\n"
+ response
+ .header("Content-Type", if (released) "application/json" else "application/x-ndjson")
+ .sendString(Mono.just(output))
+ .then()
+ }
+ } else {
+ val fixture =
+ when {
+ path.endsWith("/entries/stream") -> "entry"
+ path.endsWith("/receivables/stream") -> "receivable"
+ path.contains("transactions/") -> "send"
+ else -> "account"
+ }
+ val record =
+ if (released) {
+ fixture(fixture)
+ } else {
+ when (fixture) {
+ "account" -> Json.encodeToString(LegacyHttpFixtures.account)
+ "entry" -> Json.encodeToString(LegacyHttpFixtures.entry)
+ "receivable" -> Json.encodeToString(LegacyHttpFixtures.receivable)
+ else -> Json.encodeToString(LegacyHttpFixtures.transaction("send"))
+ }
+ }
+ val streaming = path.endsWith("/stream")
+ response
+ .header("Content-Type", if (streaming) "application/x-ndjson" else "application/json")
+ .sendString(Mono.just(if (streaming && !released) "\n \t\n$record\n\n" else record + "\n"))
+ }
+ }.bindNow()
+ try {
+ val neighbour = Neighbour(0U, server.port().toUShort(), released = released)
+ val steps = TransactionStepDefinition(ApplicationTestConfiguration().webClient(false))
+ val account = LegacyHttpFixtures.account
+ val transaction = LegacyHttpFixtures.transaction("send")
+ // When
+ val actualAccount = steps.getAccount(neighbour, account.address.publicKey)
+ val actualTransaction = steps.streamTransaction(neighbour, transaction.hash)
+ val actualEntry =
+ steps.streamAccountEntries(
+ neighbour,
+ account.address.publicKey,
+ LegacyHttpFixtures.entry.hash,
+ AttoHeight(2UL),
+ )
+ val actualReceivable = steps.streamReceivable(neighbour, account.address.publicKey, LegacyHttpFixtures.receivable.hash)
+ val blockTypes = listOf("open", "receive", "send", "change")
+ blockTypes.forEach { steps.publish(neighbour, LegacyHttpFixtures.transaction(it).toTransaction()) }
+ // Then
+ assertEquals(account, actualAccount)
+ assertEquals(transaction, actualTransaction)
+ assertEquals(LegacyHttpFixtures.entry, actualEntry)
+ assertEquals(LegacyHttpFixtures.receivable, actualReceivable)
+ val prefix = if (released) "" else "/v2"
+ val accountId =
+ if (released) {
+ account.address.publicKey.toString()
+ } else {
+ URLEncoder.encode(
+ account.address.toString(),
+ StandardCharsets.UTF_8,
+ )
+ }
+ assertEquals(
+ listOf(
+ "GET" to "$prefix/accounts/$accountId",
+ "GET" to "$prefix/transactions/${transaction.hash}/stream",
+ "GET" to "$prefix/accounts/$accountId/entries/stream?fromHeight=2&toHeight=2",
+ "GET" to "$prefix/accounts/$accountId/receivables/stream",
+ ) + blockTypes.map { "POST" to "$prefix/transactions" },
+ requests,
+ )
+ assertEquals(
+ blockTypes.map {
+ if (released) {
+ Json.parseToJsonElement(
+ fixture(it),
+ )
+ } else {
+ Json.parseToJsonElement(Json.encodeToString(LegacyHttpFixtures.transaction(it)))
+ }
+ },
+ publicationBodies,
+ )
+ } finally {
+ server.disposeNow()
+ }
+ }
+
+ private fun fixture(name: String): String = checkNotNull(javaClass.getResource("/legacy-http/$name.json")).readText()
+}
diff --git a/src/test/kotlin/cash/atto/node/transaction/prioritization/TransactionPrioritizerTest.kt b/src/test/kotlin/cash/atto/node/transaction/prioritization/TransactionPrioritizerTest.kt
index 44cb0068..4f997f69 100644
--- a/src/test/kotlin/cash/atto/node/transaction/prioritization/TransactionPrioritizerTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/prioritization/TransactionPrioritizerTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.prioritization
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -763,8 +764,7 @@ internal class TransactionPrioritizerTest {
AttoReceiveBlock(
version = account.version,
network = account.network,
- algorithm = account.algorithm,
- publicKey = account.publicKey,
+ address = AttoAddress(account.algorithm, account.publicKey),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(account.balance.raw + 10UL),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
@@ -789,14 +789,12 @@ internal class TransactionPrioritizerTest {
AttoSendBlock(
version = account.version,
network = account.network,
- algorithm = account.algorithm,
- publicKey = account.publicKey,
+ address = AttoAddress(account.algorithm, account.publicKey),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(account.balance.raw - 10UL),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = receiverPublicKey,
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, receiverPublicKey),
amount = AttoAmount(10UL),
)
Transaction(block, privateKey.sign(block.hash), AttoWorker.cpu().work(block))
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/TransactionValidationManagerTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/TransactionValidationManagerTest.kt
index da64e45a..457a557d 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/TransactionValidationManagerTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/TransactionValidationManagerTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -40,8 +41,7 @@ class TransactionValidationManagerTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = AttoPublicKey(ByteArray(32) { 1 }),
+ address = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32) { 1 })),
height = AttoHeight(2UL),
balance = AttoAmount(1UL),
timestamp = AttoInstant.now(),
@@ -57,16 +57,16 @@ class TransactionValidationManagerTest {
)
private val account =
Account(
- publicKey = block.publicKey,
+ publicKey = block.address.publicKey,
network = block.network,
version = block.version,
- algorithm = block.algorithm,
+ algorithm = block.address.algorithm,
height = 1,
balance = AttoAmount.MIN,
lastTransactionHash = block.previous,
lastTransactionTimestamp = block.timestamp.toJavaInstant().minusSeconds(1),
representativeAlgorithm = AttoAlgorithm.V1,
- representativePublicKey = block.publicKey,
+ representativePublicKey = block.address.publicKey,
)
private val accountRepository = mockk()
private val validator = mockk()
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/validator/BlockValidatorTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/validator/BlockValidatorTest.kt
index 950c6af1..dafceb7e 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/validator/BlockValidatorTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/validator/BlockValidatorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation.validator
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -49,14 +50,12 @@ internal class BlockValidatorTest {
AttoSendBlock(
version = account.version,
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight(account.height.toULong() + 1U),
balance = AttoAmount(0u),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = AttoPublicKey(ByteArray(32)),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, AttoPublicKey(ByteArray(32))),
amount = AttoAmount(100u),
)
@@ -97,14 +96,12 @@ internal class BlockValidatorTest {
AttoOpenBlock(
version = account.version,
network = account.network,
- algorithm = account.algorithm,
- publicKey = account.publicKey,
+ address = AttoAddress(account.algorithm, account.publicKey),
balance = account.balance,
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
sendHashAlgorithm = AttoAlgorithm.V1,
sendHash = AttoHash(Random.nextBytes(ByteArray(32))),
- representativeAlgorithm = account.representativeAlgorithm,
- representativePublicKey = account.representativePublicKey,
+ representativeAddress = AttoAddress(account.representativeAlgorithm, account.representativePublicKey),
)
val openTransaction =
Transaction(
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidatorTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidatorTest.kt
index 123e242b..21e89c75 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidatorTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/validator/ChangeValidatorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation.validator
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoChangeBlock
@@ -45,14 +46,12 @@ internal class ChangeValidatorTest {
AttoChangeBlock(
network = AttoNetwork.LOCAL,
version = account.version,
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(0U),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- representativeAlgorithm = AttoAlgorithm.V1,
- representativePublicKey = privateKey.toPublicKeyBlocking(),
+ representativeAddress = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
)
val node =
@@ -88,7 +87,7 @@ internal class ChangeValidatorTest {
fun `should return INVALID_REPRESENTATIVE when representative is equals previous one`() =
runBlocking {
// when
- val violation = validator.validate(account.copy(representativePublicKey = block.representativePublicKey), transaction)
+ val violation = validator.validate(account.copy(representativePublicKey = block.representativeAddress.publicKey), transaction)
// then
assertEquals(TransactionRejectionReason.INVALID_REPRESENTATIVE, violation?.reason)
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/validator/PreviousValidatorTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/validator/PreviousValidatorTest.kt
index 839f5fb2..1db22351 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/validator/PreviousValidatorTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/validator/PreviousValidatorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation.validator
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoChangeBlock
@@ -45,14 +46,12 @@ internal class PreviousValidatorTest {
AttoChangeBlock(
network = AttoNetwork.LOCAL,
version = account.version,
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(0U),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- representativeAlgorithm = AttoAlgorithm.V1,
- representativePublicKey = privateKey.toPublicKeyBlocking(),
+ representativeAddress = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
)
val node =
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/validator/ReceiveValidatorTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/validator/ReceiveValidatorTest.kt
index 7a11634b..f60dde46 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/validator/ReceiveValidatorTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/validator/ReceiveValidatorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation.validator
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -49,8 +50,7 @@ internal class ReceiveValidatorTest {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = account.version,
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(10U),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
@@ -88,8 +88,8 @@ internal class ReceiveValidatorTest {
algorithm = AttoAlgorithm.V1,
publicKey = AttoPublicKey(Random.nextBytes(32)),
timestamp = block.timestamp.toJavaInstant().minusSeconds(1),
- receiverAlgorithm = block.algorithm,
- receiverPublicKey = block.publicKey,
+ receiverAlgorithm = block.address.algorithm,
+ receiverPublicKey = block.address.publicKey,
amount = block.balance - account.balance,
)
@@ -135,7 +135,7 @@ internal class ReceiveValidatorTest {
algorithm = AttoAlgorithm.V1,
publicKey = AttoPublicKey(Random.nextBytes(32)),
timestamp = block.timestamp.toJavaInstant(),
- receiverAlgorithm = block.algorithm,
+ receiverAlgorithm = block.address.algorithm,
receiverPublicKey = AttoPublicKey(byteArray),
amount = block.balance - account.balance,
)
@@ -164,7 +164,7 @@ internal class ReceiveValidatorTest {
algorithm = AttoAlgorithm.V1,
publicKey = AttoPublicKey(Random.nextBytes(32)),
timestamp = block.timestamp.toJavaInstant().minusSeconds(1),
- receiverAlgorithm = block.algorithm,
+ receiverAlgorithm = block.address.algorithm,
receiverPublicKey = account.publicKey,
amount = AttoAmount(2UL),
)
@@ -193,7 +193,7 @@ internal class ReceiveValidatorTest {
algorithm = AttoAlgorithm.V1,
publicKey = AttoPublicKey(Random.nextBytes(32)),
timestamp = block.timestamp.toJavaInstant(),
- receiverAlgorithm = block.algorithm,
+ receiverAlgorithm = block.address.algorithm,
receiverPublicKey = account.publicKey,
amount = block.balance - account.balance,
)
diff --git a/src/test/kotlin/cash/atto/node/transaction/validation/validator/SendValidatorTest.kt b/src/test/kotlin/cash/atto/node/transaction/validation/validator/SendValidatorTest.kt
index 3a69a58e..530ccec7 100644
--- a/src/test/kotlin/cash/atto/node/transaction/validation/validator/SendValidatorTest.kt
+++ b/src/test/kotlin/cash/atto/node/transaction/validation/validator/SendValidatorTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.transaction.validation.validator
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -45,14 +46,12 @@ internal class SendValidatorTest {
AttoSendBlock(
network = AttoNetwork.LOCAL,
version = account.version,
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = AttoHeight((account.height + 1).toULong()),
balance = AttoAmount(0u),
timestamp = account.lastTransactionTimestamp.plusSeconds(1).toAtto(),
previous = account.lastTransactionHash,
- receiverAlgorithm = AttoAlgorithm.V1,
- receiverPublicKey = privateKey.toPublicKeyBlocking(),
+ receiverAddress = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
amount = AttoAmount(100u),
)
diff --git a/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionController.kt b/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionController.kt
index 668de19a..dc2fac2d 100644
--- a/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionController.kt
+++ b/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionController.kt
@@ -3,6 +3,7 @@ package cash.atto.node.unchecked
import cash.atto.commons.AttoTransaction
import cash.atto.node.bootstrap.unchecked.UncheckedTransactionProcessor
import cash.atto.node.bootstrap.unchecked.UncheckedTransactionRepository
+import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.Operation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
@@ -12,6 +13,7 @@ import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
+@Hidden
@RestController
@RequestMapping("/unchecked-transactions")
@Profile("default")
diff --git a/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionStepDefinition.kt b/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionStepDefinition.kt
index 9e3f91d3..a60cb5b1 100644
--- a/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionStepDefinition.kt
+++ b/src/test/kotlin/cash/atto/node/unchecked/UncheckedTransactionStepDefinition.kt
@@ -170,11 +170,12 @@ class UncheckedTransactionStepDefinition(
.uri("http://localhost:${neighbour.httpPort}/transactions/{hash}", hash.toString())
.retrieve()
.onStatus({ it.value() == 404 }, { Mono.empty() })
- .bodyToMono()
+ .toBodilessEntity()
+ .map { it.statusCode.is2xxSuccessful }
.timeout(Duration.ofSeconds(1))
.onErrorResume(TimeoutException::class.java) { Mono.empty() }
.blockOptional(Duration.ofSeconds(2))
- .isPresent
+ .orElse(false)
private fun describeDiscoveryState(
neighbour: Neighbour,
diff --git a/src/test/kotlin/cash/atto/node/vote/keeping/VoteKeeperTest.kt b/src/test/kotlin/cash/atto/node/vote/keeping/VoteKeeperTest.kt
index eb378b38..a1095e58 100644
--- a/src/test/kotlin/cash/atto/node/vote/keeping/VoteKeeperTest.kt
+++ b/src/test/kotlin/cash/atto/node/vote/keeping/VoteKeeperTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.vote.keeping
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -103,7 +104,7 @@ class VoteKeeperTest {
coVerify(exactly = 1) {
fixture.signer.sign(
match {
- it.publicKey == thisNode.publicKey &&
+ it.address.publicKey == thisNode.publicKey &&
it.blockHash == missing.lastTransactionHash &&
it.timestamp == AttoVote.finalTimestamp
},
@@ -132,8 +133,7 @@ class VoteKeeperTest {
AttoSignedVote(
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = representative.publicKey,
+ address = AttoAddress(AttoAlgorithm.V1, representative.publicKey),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = missing.lastTransactionHash,
timestamp = AttoVote.finalTimestamp,
diff --git a/src/test/kotlin/cash/atto/node/vote/weight/VoteWeighterTest.kt b/src/test/kotlin/cash/atto/node/vote/weight/VoteWeighterTest.kt
index a1bd1c2a..e330221b 100644
--- a/src/test/kotlin/cash/atto/node/vote/weight/VoteWeighterTest.kt
+++ b/src/test/kotlin/cash/atto/node/vote/weight/VoteWeighterTest.kt
@@ -1,5 +1,6 @@
package cash.atto.node.vote.weight
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoBlock
@@ -179,7 +180,7 @@ class VoteWeighterTest {
balance: AttoAmount,
): AccountUpdated {
val block = mockk()
- every { block.representativePublicKey } returns representative
+ every { block.representativeAddress.publicKey } returns representative
every { block.balance } returns balance
return accountUpdated(block, previousRepresentative, representative, balance)
}
@@ -215,8 +216,7 @@ class VoteWeighterTest {
AttoReceiveBlock(
version = 0U.toAttoVersion(),
network = AttoNetwork.LOCAL,
- algorithm = AttoAlgorithm.V1,
- publicKey = randomPublicKey(),
+ address = AttoAddress(AttoAlgorithm.V1, randomPublicKey()),
height = AttoHeight(2UL),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/kotlin/cash/atto/protocol/AttoMessageIngressTestSupport.kt b/src/test/kotlin/cash/atto/protocol/AttoMessageIngressTestSupport.kt
index f2887814..ac8ad8d5 100644
--- a/src/test/kotlin/cash/atto/protocol/AttoMessageIngressTestSupport.kt
+++ b/src/test/kotlin/cash/atto/protocol/AttoMessageIngressTestSupport.kt
@@ -1,5 +1,6 @@
package cash.atto.protocol
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -45,8 +46,7 @@ internal fun localTransaction(): AttoTransaction {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
@@ -88,8 +88,7 @@ private fun vote(
): AttoVote =
AttoVote(
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
blockAlgorithm = AttoAlgorithm.V1,
blockHash = AttoHash(Random.nextBytes(ByteArray(32))),
timestamp = timestamp,
diff --git a/src/test/kotlin/cash/atto/protocol/AttoTransactionStreamResponseTest.kt b/src/test/kotlin/cash/atto/protocol/AttoTransactionStreamResponseTest.kt
index 744ad0ef..59ea04dc 100644
--- a/src/test/kotlin/cash/atto/protocol/AttoTransactionStreamResponseTest.kt
+++ b/src/test/kotlin/cash/atto/protocol/AttoTransactionStreamResponseTest.kt
@@ -1,5 +1,6 @@
package cash.atto.protocol
+import cash.atto.commons.AttoAddress
import cash.atto.commons.AttoAlgorithm
import cash.atto.commons.AttoAmount
import cash.atto.commons.AttoHash
@@ -44,8 +45,7 @@ class AttoTransactionStreamResponseTest {
AttoReceiveBlock(
network = AttoNetwork.LOCAL,
version = 0U.toAttoVersion(),
- algorithm = AttoAlgorithm.V1,
- publicKey = privateKey.toPublicKeyBlocking(),
+ address = AttoAddress(AttoAlgorithm.V1, privateKey.toPublicKeyBlocking()),
height = 2U.toAttoHeight(),
balance = AttoAmount.MAX,
timestamp = AttoInstant.now(),
diff --git a/src/test/resources/legacy-http/account.json b/src/test/resources/legacy-http/account.json
new file mode 100644
index 00000000..d7ccab46
--- /dev/null
+++ b/src/test/resources/legacy-http/account.json
@@ -0,0 +1 @@
+{"publicKey":"0101010101010101010101010101010101010101010101010101010101010101","network":"LOCAL","version":0,"algorithm":"V1","height":2,"balance":10,"lastTransactionHash":"0303030303030303030303030303030303030303030303030303030303030303","lastTransactionTimestamp":1234567890000,"representativeAlgorithm":"V1","representativePublicKey":"0202020202020202020202020202020202020202020202020202020202020202"}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/change.hex b/src/test/resources/legacy-http/change.hex
new file mode 100644
index 00000000..b5a1407b
--- /dev/null
+++ b/src/test/resources/legacy-http/change.hex
@@ -0,0 +1 @@
+0303000000010101010101010101010101010101010101010101010101010101010101010102000000000000000A000000000000005004FB711F0100000303030303030303030303030303030303030303030303030303030303030303000202020202020202020202020202020202020202020202020202020202020202040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040505050505050505
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/change.json b/src/test/resources/legacy-http/change.json
new file mode 100644
index 00000000..3457ca93
--- /dev/null
+++ b/src/test/resources/legacy-http/change.json
@@ -0,0 +1 @@
+{"block":{"type":"CHANGE","network":"LOCAL","version":0,"algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","height":2,"balance":10,"timestamp":1234567890000,"previous":"0303030303030303030303030303030303030303030303030303030303030303","representativeAlgorithm":"V1","representativePublicKey":"0202020202020202020202020202020202020202020202020202020202020202","address":"atto://aaaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqc6zspultg","representativeAddress":"atto://aabaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaevjhdj47s"},"signature":"04040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404","work":"0505050505050505"}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/entry.json b/src/test/resources/legacy-http/entry.json
new file mode 100644
index 00000000..8f1a0ebc
--- /dev/null
+++ b/src/test/resources/legacy-http/entry.json
@@ -0,0 +1 @@
+{"hash":"0303030303030303030303030303030303030303030303030303030303030303","algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","height":2,"blockType":"SEND","subjectAlgorithm":"V1","subjectPublicKey":"0202020202020202020202020202020202020202020202020202020202020202","previousBalance":13,"balance":10,"timestamp":1234567890000,"address":"atto://aaaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqc6zspultg","subjectAddress":"atto://aabaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaevjhdj47s"}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/open.hex b/src/test/resources/legacy-http/open.hex
new file mode 100644
index 00000000..ce5a2cd0
--- /dev/null
+++ b/src/test/resources/legacy-http/open.hex
@@ -0,0 +1 @@
+000300000001010101010101010101010101010101010101010101010101010101010101010A000000000000005004FB711F010000000303030303030303030303030303030303030303030303030303030303030303000202020202020202020202020202020202020202020202020202020202020202040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040505050505050505
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/open.json b/src/test/resources/legacy-http/open.json
new file mode 100644
index 00000000..8f7f0fb3
--- /dev/null
+++ b/src/test/resources/legacy-http/open.json
@@ -0,0 +1 @@
+{"block":{"type":"OPEN","network":"LOCAL","version":0,"algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","balance":10,"timestamp":1234567890000,"sendHashAlgorithm":"V1","sendHash":"0303030303030303030303030303030303030303030303030303030303030303","representativeAlgorithm":"V1","representativePublicKey":"0202020202020202020202020202020202020202020202020202020202020202","height":1,"address":"atto://aaaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqc6zspultg","representativeAddress":"atto://aabaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaevjhdj47s"},"signature":"04040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404","work":"0505050505050505"}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/receivable.json b/src/test/resources/legacy-http/receivable.json
new file mode 100644
index 00000000..2f494f3c
--- /dev/null
+++ b/src/test/resources/legacy-http/receivable.json
@@ -0,0 +1 @@
+{"network":"LOCAL","hash":"0303030303030303030303030303030303030303030303030303030303030303","version":0,"algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","timestamp":1234567890000,"receiverAlgorithm":"V1","receiverPublicKey":"0202020202020202020202020202020202020202020202020202020202020202","amount":3}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/receive.hex b/src/test/resources/legacy-http/receive.hex
new file mode 100644
index 00000000..5b7b7345
--- /dev/null
+++ b/src/test/resources/legacy-http/receive.hex
@@ -0,0 +1 @@
+0103000000010101010101010101010101010101010101010101010101010101010101010102000000000000000A000000000000005004FB711F0100000303030303030303030303030303030303030303030303030303030303030303000303030303030303030303030303030303030303030303030303030303030303040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040505050505050505
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/receive.json b/src/test/resources/legacy-http/receive.json
new file mode 100644
index 00000000..edc92d7b
--- /dev/null
+++ b/src/test/resources/legacy-http/receive.json
@@ -0,0 +1 @@
+{"block":{"type":"RECEIVE","network":"LOCAL","version":0,"algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","height":2,"balance":10,"timestamp":1234567890000,"previous":"0303030303030303030303030303030303030303030303030303030303030303","sendHashAlgorithm":"V1","sendHash":"0303030303030303030303030303030303030303030303030303030303030303","address":"atto://aaaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqc6zspultg"},"signature":"04040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404","work":"0505050505050505"}
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/send.hex b/src/test/resources/legacy-http/send.hex
new file mode 100644
index 00000000..c17eaf1b
--- /dev/null
+++ b/src/test/resources/legacy-http/send.hex
@@ -0,0 +1 @@
+0203000000010101010101010101010101010101010101010101010101010101010101010102000000000000000A000000000000005004FB711F01000003030303030303030303030303030303030303030303030303030303030303030002020202020202020202020202020202020202020202020202020202020202020300000000000000040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040505050505050505
\ No newline at end of file
diff --git a/src/test/resources/legacy-http/send.json b/src/test/resources/legacy-http/send.json
new file mode 100644
index 00000000..f4652b91
--- /dev/null
+++ b/src/test/resources/legacy-http/send.json
@@ -0,0 +1 @@
+{"block":{"type":"SEND","network":"LOCAL","version":0,"algorithm":"V1","publicKey":"0101010101010101010101010101010101010101010101010101010101010101","height":2,"balance":10,"timestamp":1234567890000,"previous":"0303030303030303030303030303030303030303030303030303030303030303","receiverAlgorithm":"V1","receiverPublicKey":"0202020202020202020202020202020202020202020202020202020202020202","amount":3,"address":"atto://aaaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqc6zspultg","receiverAddress":"atto://aabaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaeaqcaibaevjhdj47s"},"signature":"04040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404040404","work":"0505050505050505"}
\ No newline at end of file