antd 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ab6786553e76394691c28a2968384dd279738e876ecf961e74a0b7b46904cc0e
4
- data.tar.gz: a04836fdba38a5457a3cfda27c3adde84bc8175a87dcd1c58e719fb315cc1f0a
3
+ metadata.gz: 88248e4cfde28e4e91fbdf8009f6ae4612760b8bc0d5aacdc2ebbe2145f7e785
4
+ data.tar.gz: 72be5e95f26b60955a218cdaca951f9a62805ab55d0105dd14fbfa54d9f86ccf
5
5
  SHA512:
6
- metadata.gz: '0806f4881413dd24b52a385319ee23ca30de479dea639b54ef0088bd31f8f0cdba73c0d458843082f697e6a92a3bb4c1f5c34dd77532d38d8032dcb4845f3c78'
7
- data.tar.gz: 12fffe89716557c9dc2716a99f5f8b39a4958251387050f8828f45ff69628e2350e5aa6dc370f55a89d3abfc06fbb214770bf9cd1c31e516e794fc09daaf9fd4
6
+ metadata.gz: 44c61f831f79bb930096bca79eaa731efe59707b52a4029339477cfe3aedfb38f38ead592d2ac944bcad7afcf0180e876e9aadc1fc8babca62afd684d8fa1c0b
7
+ data.tar.gz: 3f4cd055d0f1868c53aa343582b6d28e3aafc883dcdb63b624f04fb74714f8dd24f93d6dd6f99055874856f378b184643c9d630ea7bbc52e049388c47e56b2b7
data/README.md CHANGED
@@ -18,7 +18,7 @@ gem install antd
18
18
 
19
19
  ## Compatibility
20
20
 
21
- This gem talks to a running [antd](https://github.com/WithAutonomi/ant-sdk/tree/main/antd) daemon; it does not join the network itself. Ruby 3.1+. Tested against antd 0.12.x. The REST client has no runtime dependencies; the gRPC transport (`Antd::GrpcClient`) needs the `grpc` gem, which is deliberately not a runtime dependency of this gem — add `gem "grpc"` yourself to use it.
21
+ This gem talks to a running [antd](https://github.com/WithAutonomi/ant-sdk/tree/main/antd) daemon; it does not join the network itself. Ruby 3.1+. Tested against antd 0.12.x; the pointer methods need antd 0.16.0 or later, the first release with pointers. The REST client has no runtime dependencies; the gRPC transport (`Antd::GrpcClient`) needs the `grpc` gem, which is deliberately not a runtime dependency of this gem — add `gem "grpc"` yourself to use it.
22
22
 
23
23
  ## Quick Start
24
24
 
@@ -53,18 +53,15 @@ Install the gRPC gem (listed as an optional development dependency):
53
53
  gem install grpc grpc-tools
54
54
  ```
55
55
 
56
- Generate the Ruby protobuf/gRPC stubs from the proto definitions:
56
+ The Ruby protobuf/gRPC stubs in `lib/antd/v1/` are generated from the proto
57
+ definitions and committed. After changing the protos, regenerate them and
58
+ commit the result (CI fails when they drift):
57
59
 
58
60
  ```bash
59
- grpc_tools_ruby_protoc \
60
- -I../../antd/proto \
61
- --ruby_out=lib --grpc_out=lib \
62
- antd/v1/common.proto antd/v1/health.proto antd/v1/data.proto \
63
- antd/v1/chunks.proto antd/v1/files.proto
61
+ gem install grpc-tools -v 1.84.0 # the version the script pins
62
+ antd-ruby/scripts/generate-protos.sh
64
63
  ```
65
64
 
66
- The generated files are expected under `lib/antd/v1/`.
67
-
68
65
  ### Usage
69
66
 
70
67
  ```ruby
@@ -96,6 +93,16 @@ the daemon sent — start with `Partial upload:` becomes
96
93
  `ABORTED`, including one that only mentions `Partial upload:` later in its
97
94
  text, stays a generic `Antd::AntdError`).
98
95
 
96
+ The pointer and close-group errors share gRPC status codes with older ones, so
97
+ the daemon names them in an `x-antd-error-code` trailer
98
+ (`GRPC::BadStatus#metadata`). The client reads it on every call and, when it
99
+ agrees with the status code, raises the same typed error as REST:
100
+ `FAILED_PRECONDITION` + `POINTER_FINAL` → `PointerFinalError`, + `POINTER_FORKED`
101
+ → `PointerForkedError`, `ABORTED` + `CONFLICT` → `ConflictError`, and
102
+ `UNAVAILABLE` + `CLOSE_GROUP_SHORTFALL` → `CloseGroupShortfallError` (`retryable`
103
+ when the details close with `(paid attempt retained...)`). Without the trailer,
104
+ `FAILED_PRECONDITION` stays a `PaymentError` and `UNAVAILABLE` a `NetworkError`.
105
+
99
106
  > **Note:** Wallet operations (address, balance, approve) and payment_mode are available via REST only.
100
107
 
101
108
  ## Prerequisites
@@ -153,6 +160,68 @@ client = Antd::Client.new(base_url: "http://custom-host:9090", timeout: 30)
153
160
  | `file_get_public(address, dest_path)` | Download a public file by address |
154
161
  | `file_cost(path, is_public, payment_mode: :auto)` | Estimate upload cost — returns `UploadCostEstimate` with size, chunks, gas, payment mode |
155
162
 
163
+ **`sha256` on upload results.** `DataPutResult`, `DataPutPublicResult`,
164
+ `FilePutResult`, `FilePutPublicResult` and `FinalizeUploadResult` (from
165
+ `finalize_upload` and `finalize_merkle_upload`) have a `sha256` field: the
166
+ plaintext's SHA-256 (hex); requires antd 0.17.0 or later, none on older
167
+ daemons (`nil`, over REST and gRPC alike).
168
+
169
+ ### Pointers
170
+
171
+ A pointer is a small, owner-signed, mutable reference. Its address is derived
172
+ from the owner's key and never changes; what it points at (a chunk, such as a
173
+ public file's data map, or another pointer) can be changed by the owner, and
174
+ the owner can hand it over to another pointer for good. The daemon holds the
175
+ owner keys, loaded at startup with `antd --pointer-keys <file-or-dir>` (files
176
+ in the format `ant pointer keygen` writes), so every write names the pointer by
177
+ its address (`owner`), never by a key. An address the daemon holds no key for
178
+ is a `BadRequestError`.
179
+
180
+ **Every write pays** (about the price of one chunk), and every attempt pays
181
+ again. The SDK never retries a request, and you should not retry
182
+ `pointer_create`, `pointer_update`, `pointer_transfer` or `pointer_finalize`
183
+ automatically either. Reads are free to retry; one during an update or churn
184
+ can fail with `CloseGroupShortfallError`.
185
+
186
+ Both `Antd::Client` and `Antd::GrpcClient` have these methods:
187
+
188
+ | Method | Description |
189
+ |--------|-------------|
190
+ | `pointer_keys` | Addresses of the pointers this daemon holds keys for, so can write — `Array<String>` |
191
+ | `pointer_create(owner, target, kind: nil)` | Create a pointer, paid by the daemon wallet — returns `PointerWriteResult` (`address`, `state_id`, `counter`). `AlreadyExistsError`, before paying, if it exists. `kind` is `PointerKind::CHUNK` (the default) or `PointerKind::POINTER` |
192
+ | `pointer_update(owner, target, kind: nil)` | Point a pointer at a new target, creating it if needed — `PointerWriteResult`. `PointerFinalError`, usually before paying, once it was handed over or frozen |
193
+ | `pointer_transfer(owner, recipient)` | Hand a pointer over for good to the recipient's pointer, which must exist. Irreversible. Returns `PointerTransferResult` with the close group's `finality` (nil, with `finality_error`, if that check failed; the transfer stands) |
194
+ | `pointer_get(address)` | Read a pointer — `PointerRecord` (`counter`, `target`, `kind`/`kind_tag`, `is_final` / `final?`, `transferred_to`, the owner's public key). `NotFoundError` if there is none |
195
+ | `pointer_resolve(address)` | Follow a chain of pointers to the target at its end — `PointerTarget` (`kind`, `kind_tag`, `target`) |
196
+ | `pointer_finality(address)` | Ask the whole close group where a pointer stands — `PointerFinality`. Check `final?` before relying on a transfer |
197
+ | `pointer_controller(address)` | Follow transfers to the pointer whose owner now decides — `PointerController` (`pointer`, `transfers`, `frozen`) |
198
+ | `pointer_prepare(owner, op, target: nil, kind: nil, recipient: nil, include_signed_quotes: false)` | External signer: the daemon signs a `PointerOp::CREATE`, `UPDATE` or `TRANSFER` and quotes it — `PointerPrepareResult` (wave-batch `payments` for `payForQuotes()`; `signed_quotes` when asked). Needs no daemon wallet. Other writes to the pointer raise `ConflictError` until it is finalized or expires (one hour) |
199
+ | `pointer_finalize(upload_id, tx_hashes)` | External signer: store the prepared write once paid — `PointerFinalizeResult`. A write that falls short after payment raises `CloseGroupShortfallError` with `retryable`: repeat the same call to store it against the same payment |
200
+
201
+ Counters are `Integer`s. The daemon sends them as decimal strings, because a
202
+ final state (a transfer or a freeze) sits at `Antd::POINTER_FINAL_COUNTER`
203
+ (2^64 − 1), past what a JSON number keeps exactly in many languages. A counter
204
+ that is not a decimal u64 raises `InternalError`; it never reads as 0.
205
+
206
+ `PointerFinality#status` is one of the `Antd::PointerFinalityStatus` strings:
207
+ `OPEN` (with the corroborated `counter`, or nil), `SETTLING`, `UNCONFIRMED` and
208
+ `FINAL` (with the one final `state`), or `FORKED` (with every final state in
209
+ `states` and the `majority`). Only `FINAL` means a transfer is beyond dispute.
210
+ A status a newer daemon adds is kept verbatim (`status_known?` is false), so
211
+ give a `case` over it an `else` branch. Unset fields read as `nil` on both
212
+ transports: REST sends `null`, gRPC an empty string or no message.
213
+
214
+ The daemon accepts addresses with a `0x` prefix but always returns bare hex;
215
+ normalise before comparing.
216
+
217
+ ```ruby
218
+ owner = client.pointer_keys.first
219
+ client.pointer_create(owner, client.data_put_public("v1").address) # pays
220
+ client.pointer_update(owner, client.data_put_public("v2").address) # pays again
221
+ puts client.data_get_public(client.pointer_resolve(owner).target) # "v2"
222
+ puts client.pointer_finality(owner).status # "open"
223
+ ```
224
+
156
225
  ## Error Handling
157
226
 
158
227
  All errors inherit from `Antd::AntdError` and can be caught by type:
@@ -180,6 +249,18 @@ end
180
249
  | `InternalError` | 500 | Server error |
181
250
  | `NetworkError` | 502 | Network unreachable |
182
251
  | `PartialUploadError` | 502 (`code: "PARTIAL_UPLOAD"`) | Finalize stored some chunks but not all — subclass of `NetworkError` |
252
+ | `ServiceUnavailableError` | 503 | Wallet not configured |
253
+ | `PointerFinalError` | 409 (`code: "POINTER_FINAL"`) / gRPC `FAILED_PRECONDITION` | The pointer is transferred or frozen; nothing can change it |
254
+ | `PointerForkedError` | 409 (`code: "POINTER_FORKED"`) / gRPC `FAILED_PRECONDITION` | The owner signed two final states and no majority holds either — subclass of `ForkError` |
255
+ | `ConflictError` | 409 (`code: "CONFLICT"`) / gRPC `ABORTED` | A pointer write while a prepared write to it awaits payment, or an update that lost to a newer state |
256
+ | `CloseGroupShortfallError` | 503 (`code: "CLOSE_GROUP_SHORTFALL"`) / gRPC `UNAVAILABLE` | Too few of the close group answered or stored; `retryable` is true only for a pointer finalize that kept the paid state |
257
+
258
+ The pointer errors are read from the error body's `code` (gRPC: the
259
+ `x-antd-error-code` trailer), so a 409 with one of those codes is not an
260
+ `AlreadyExistsError`. `CloseGroupShortfallError` is not only for pointers: a
261
+ daemon with the pointer API reports a close group that fell short on any call
262
+ (a chunk store, say) this way, where older daemons sent a 500
263
+ (`InternalError`). It is not a `ServiceUnavailableError`, so rescue it by name.
183
264
 
184
265
  ### Partial uploads
185
266
 
@@ -256,6 +337,71 @@ See [`docs/external-signer-flow.md` section 6](../docs/external-signer-flow.md#6
256
337
  for the daemon contract and `examples/07_external_signer.rb` for a
257
338
  `finalize_with_retry` helper.
258
339
 
340
+ ## Manifests
341
+
342
+ A manifest (ADR-0006) describes a set of files in one `.ant` file or
343
+ `ant://` link: each entry has an optional path and size, and either an
344
+ embedded DataMap (from a private upload; the manifest is then the key to the
345
+ file) or a public file's DataMap address. The daemon builds and decodes
346
+ manifests, so the SDK never handles the format itself. These methods need
347
+ antd 0.16.0 or later.
348
+
349
+ **Nothing is uploaded or paid for.** Building one from DataMaps and addresses
350
+ you already hold is free. Embedding roots (on build) and `resolve` (on
351
+ decode) read from the network, so either can time out; retrying is safe.
352
+
353
+ Both `Antd::Client` and `Antd::GrpcClient` have these methods:
354
+
355
+ | Method | Description |
356
+ |--------|-------------|
357
+ | `build_manifest(entries, name: nil, torrent_info_hashes: nil, embed_roots: true)` | Build a manifest — returns `BuiltManifest` (`manifest`, the raw `.ant` bytes; `link`, or nil when it would exceed 1,500 bytes; `entries`, sorted by effective name). Each entry is a `ManifestEntryInput` or a Hash with `path`, `size`, and exactly one of `data_map` (hex) or `address` (hex); both or neither raises `BadRequestError` (400, the daemon's wording) before anything is sent. By default the daemon resolves each shrunk DataMap and embeds its root when it is at most 64 KiB; `embed_roots: false` embeds them as given |
358
+ | `decode_manifest(manifest, resolve: false)` | Decode `.ant` bytes — returns `DecodedManifest` (`source`, `name`, `torrent_info_hash_v1`/`_v2`, `entries`) |
359
+ | `decode_manifest_link(link, resolve: false)` | Decode an `ant://manifest/` link, a file link or a bare 64-hex address (a `ManifestSource::FILE_LINK`: one public entry, no path) |
360
+
361
+ Each entry comes back as a `ManifestEntryInfo`: `effective_name` (the path,
362
+ or the content address when there is none), `path`, `size` (what the
363
+ manifest records: the creator's claim), `kind` (`ManifestEntryKind::EMBEDDED`
364
+ or `PUBLIC`), `content_address`, `data_map` (decode only, embedded entries
365
+ only, in the hex form `data_get` and `file_get` take), `exact_size`, and
366
+ `error`. With `resolve: true` the daemon fetches each DataMap (not the
367
+ content) to fill in `exact_size`; an entry that fails gets an `error` instead
368
+ of failing the call.
369
+
370
+ An entry can record the file's plaintext SHA-256: give `sha256` (hex) on a
371
+ `ManifestEntryInput` or Hash entry, and read it back as `sha256` on the
372
+ `ManifestEntryInfo`, from both build and decode. Both require antd 0.17.0 or
373
+ later. The SDK sends `sha256` only when it is set and non-empty, and passes it
374
+ through unchecked: the daemon validates it (upper or lower case is accepted,
375
+ lowercase comes back) and a bad one raises `BadRequestError`. An entry with no
376
+ recorded hash reads `nil`.
377
+
378
+ `manifest` is always raw bytes: the SDK base64-encodes it for REST and sends
379
+ it as-is over gRPC. Sizes are `Integer`s, and anything a manifest leaves unset
380
+ is `nil` on both transports, so a missing `size` or `exact_size` is `nil`,
381
+ never `0`. An entry the daemon rejects (a bad path such as `../x`, a malformed
382
+ DataMap or address) raises `BadRequestError` (gRPC `INVALID_ARGUMENT`) with
383
+ the daemon's message, which names `entries[i]`. The SDK's own checks (both or
384
+ neither of `data_map` and `address`, an empty manifest or link) raise the same
385
+ error with the daemon's exact text, so the two cannot be told apart.
386
+
387
+ Over gRPC, a manifest can be up to 64 MiB, past gRPC's 4 MiB default, so the
388
+ client talks to ManifestService on a channel of its own with the send and
389
+ receive limits raised to `Antd::MANIFEST_GRPC_MAX_MESSAGE` (256 MiB). The
390
+ other services keep the defaults.
391
+
392
+ ```ruby
393
+ a = client.data_put_public("one").address # pays
394
+ b = client.data_put_public("two").address # pays
395
+ built = client.build_manifest(
396
+ [{ path: "notes/one.txt", address: a }, { path: "notes/two.txt", address: b }],
397
+ name: "notes"
398
+ ) # free
399
+ File.binwrite("notes.ant", built.manifest)
400
+ client.decode_manifest_link(built.link, resolve: true).entries.each do |e|
401
+ puts "#{e.effective_name}: #{e.exact_size} bytes"
402
+ end
403
+ ```
404
+
259
405
  ## Examples
260
406
 
261
407
  See the [examples/](examples/) directory:
@@ -266,3 +412,5 @@ See the [examples/](examples/) directory:
266
412
  - `04_files.rb` — File upload and download
267
413
  - `06_private_data.rb` — Private data put/get
268
414
  - `07_external_signer.rb` — External-signer prepare/pay/finalize with a bounded partial-upload retry
415
+ - `08_pointers.rb` — Create a pointer, update it, resolve it and check its finality. Run with `ANTD_POINTER_OWNER=<address>` (one of `pointer_keys`); `ANTD_BASE_URL` overrides the daemon URL. Each write pays
416
+ - `09_manifests.rb` — Store two pieces of public data, build a manifest of them, print its link and entries, and decode the link with `resolve`. `ANTD_BASE_URL` overrides the daemon URL. The two uploads pay; the manifest calls do not
data/lib/antd/client.rb CHANGED
@@ -61,7 +61,8 @@ module Antd
61
61
  DataPutResult.new(
62
62
  data_map: j["data_map"] || "",
63
63
  chunks_stored: (j["chunks_stored"] || 0).to_i,
64
- payment_mode_used: j["payment_mode_used"] || ""
64
+ payment_mode_used: j["payment_mode_used"] || "",
65
+ sha256: presence(j["sha256"])
65
66
  )
66
67
  end
67
68
 
@@ -120,7 +121,8 @@ module Antd
120
121
  DataPutPublicResult.new(
121
122
  address: j["address"] || "",
122
123
  chunks_stored: (j["chunks_stored"] || 0).to_i,
123
- payment_mode_used: j["payment_mode_used"] || ""
124
+ payment_mode_used: j["payment_mode_used"] || "",
125
+ sha256: presence(j["sha256"])
124
126
  )
125
127
  end
126
128
 
@@ -248,7 +250,8 @@ module Antd
248
250
  storage_cost_atto: j["storage_cost_atto"] || "",
249
251
  gas_cost_wei: j["gas_cost_wei"] || "",
250
252
  chunks_stored: (j["chunks_stored"] || 0).to_i,
251
- payment_mode_used: j["payment_mode_used"] || ""
253
+ payment_mode_used: j["payment_mode_used"] || "",
254
+ sha256: presence(j["sha256"])
252
255
  )
253
256
  end
254
257
 
@@ -273,7 +276,8 @@ module Antd
273
276
  storage_cost_atto: j["storage_cost_atto"] || "",
274
277
  gas_cost_wei: j["gas_cost_wei"] || "",
275
278
  chunks_stored: (j["chunks_stored"] || 0).to_i,
276
- payment_mode_used: j["payment_mode_used"] || ""
279
+ payment_mode_used: j["payment_mode_used"] || "",
280
+ sha256: presence(j["sha256"])
277
281
  )
278
282
  end
279
283
 
@@ -417,8 +421,250 @@ module Antd
417
421
  parse_finalize_response(j)
418
422
  end
419
423
 
424
+ # --- Pointers ---
425
+ #
426
+ # Owner-signed, paid, mutable references (antd 0.16.0 or
427
+ # later). The daemon signs with owner keys it loaded at
428
+ # startup (+antd --pointer-keys <file-or-dir>+), so a write names the
429
+ # pointer by its address (+owner+); +pointer_keys+ lists the pointers it
430
+ # can write.
431
+ #
432
+ # Every write pays, about the price of one chunk, and every attempt pays
433
+ # again. This client never retries a request, and callers must not retry
434
+ # +pointer_create+, +pointer_update+, +pointer_transfer+ or
435
+ # +pointer_finalize+ automatically (the one exception: a finalize that
436
+ # raised +CloseGroupShortfallError+ with +retryable+). Reads are free to
437
+ # retry.
438
+ #
439
+ # Addresses are 64 hex characters. The daemon accepts a 0x prefix but
440
+ # always returns bare hex, so normalise before comparing.
441
+
442
+ # The addresses of the pointers this daemon holds owner keys for. Only
443
+ # these can be written.
444
+ # @return [Array<String>]
445
+ def pointer_keys
446
+ j = do_json(:get, "/v1/pointers/keys")
447
+ (j["keys"] || []).map { |k| k["address"] || "" }
448
+ end
449
+
450
+ # Create the pointer at +owner+, pointing at +target+, paid by the daemon
451
+ # wallet. Pays; do not retry automatically.
452
+ # @param owner [String] address of the pointer to write
453
+ # @param target [String] address to point at
454
+ # @param kind [String, nil] +PointerKind::CHUNK+ (the daemon's default when
455
+ # nil) or +PointerKind::POINTER+
456
+ # @return [PointerWriteResult]
457
+ # @raise [AlreadyExistsError] before paying, if the pointer exists
458
+ # @raise [BadRequestError] if the daemon holds no key for +owner+
459
+ def pointer_create(owner, target, kind: nil)
460
+ pointer_write("/v1/pointers", owner, target, kind)
461
+ end
462
+
463
+ # Point the pointer at +owner+ at +target+, paid by the daemon wallet,
464
+ # creating it if it does not exist. Pays; do not retry automatically.
465
+ # @param owner [String]
466
+ # @param target [String]
467
+ # @param kind [String, nil] see +pointer_create+
468
+ # @return [PointerWriteResult]
469
+ # @raise [PointerFinalError] if the pointer was handed over or frozen
470
+ # (usually before paying; see +PointerFinalError+)
471
+ # @raise [ConflictError] if a prepared write to it awaits payment (refused
472
+ # before paying), or the update lost to a newer state while in flight
473
+ # (possibly after paying); read the pointer before writing again
474
+ def pointer_update(owner, target, kind: nil)
475
+ pointer_write("/v1/pointers/update", owner, target, kind)
476
+ end
477
+
478
+ # Hand the pointer at +owner+ over to the pointer at +recipient+, for
479
+ # good, paid by the daemon wallet. Readers of +owner+'s address are
480
+ # redirected to the recipient's pointer, which only its owner can move.
481
+ # Irreversible once stored. Pays; do not retry automatically.
482
+ #
483
+ # Refused before paying if +recipient+ does not exist or leads back
484
+ # (+BadRequestError+), and usually if the pointer is already final
485
+ # (+PointerFinalError+). A +CloseGroupShortfallError+ means too few of the
486
+ # close group answered or stored it. That can happen before paying (the
487
+ # transfer checks every peer first) or after, so check the pointer with
488
+ # +pointer_finality+ before paying again.
489
+ #
490
+ # @param owner [String]
491
+ # @param recipient [String] address of the recipient's pointer
492
+ # @return [PointerTransferResult]
493
+ def pointer_transfer(owner, recipient)
494
+ j = do_json(:post, "/v1/pointers/transfer", { owner: owner, recipient: recipient })
495
+ PointerTransferResult.new(
496
+ address: j["address"] || "",
497
+ state_id: j["state_id"] || "",
498
+ finality: j["finality"].is_a?(Hash) ? parse_pointer_finality(j["finality"]) : nil,
499
+ finality_error: presence(j["finality_error"])
500
+ )
501
+ end
502
+
503
+ # Read the pointer at +address+.
504
+ # @param address [String]
505
+ # @return [PointerRecord]
506
+ # @raise [NotFoundError] if no pointer exists there
507
+ def pointer_get(address)
508
+ j = do_json(:get, "/v1/pointers/#{address}")
509
+ PointerRecord.new(
510
+ address: j["address"] || "",
511
+ owner: j["owner"] || "",
512
+ counter: Antd.parse_pointer_counter("counter", j["counter"]),
513
+ kind: j["kind"] || "",
514
+ kind_tag: (j["kind_tag"] || 0).to_i,
515
+ target: j["target"] || "",
516
+ state_id: j["state_id"] || "",
517
+ is_final: j["is_final"] == true,
518
+ transferred_to: presence(j["transferred_to"])
519
+ )
520
+ end
521
+
522
+ # Follow a chain of pointers from +address+ to the target at its end.
523
+ # @param address [String]
524
+ # @return [PointerTarget]
525
+ # @raise [NotFoundError] if a pointer on the chain does not exist
526
+ def pointer_resolve(address)
527
+ j = do_json(:get, "/v1/pointers/#{address}/resolve")
528
+ PointerTarget.new(kind: j["kind"] || "", kind_tag: (j["kind_tag"] || 0).to_i, target: j["target"] || "")
529
+ end
530
+
531
+ # Ask the whole close group where the pointer at +address+ stands. Check
532
+ # it before relying on a transfer: only +PointerFinality#final?+ means the
533
+ # transfer is beyond dispute.
534
+ # @param address [String]
535
+ # @return [PointerFinality]
536
+ def pointer_finality(address)
537
+ parse_pointer_finality(do_json(:get, "/v1/pointers/#{address}/finality"))
538
+ end
539
+
540
+ # Follow the transfers from +address+ to the pointer whose owner now
541
+ # decides what it resolves to.
542
+ # @param address [String]
543
+ # @return [PointerController]
544
+ def pointer_controller(address)
545
+ j = do_json(:get, "/v1/pointers/#{address}/controller")
546
+ PointerController.new(
547
+ pointer: j["pointer"] || "",
548
+ transfers: (j["transfers"] || []).grep(String),
549
+ frozen: j["frozen"] == true
550
+ )
551
+ end
552
+
553
+ # External signer: sign a pointer write with the daemon's loaded owner key
554
+ # and quote it, without paying. The external signer pays +payments+ with
555
+ # +payForQuotes()+ and then calls +pointer_finalize+. The daemon needs no
556
+ # wallet. While the prepared write awaits payment (up to an hour), other
557
+ # writes to the same pointer raise +ConflictError+.
558
+ #
559
+ # @param owner [String] address of the pointer to write
560
+ # @param op [String] +PointerOp::CREATE+, +UPDATE+ or +TRANSFER+
561
+ # @param target [String, nil] create / update: the address to point at
562
+ # @param kind [String, nil] create / update: see +pointer_create+
563
+ # @param recipient [String, nil] transfer: the recipient's pointer
564
+ # @param include_signed_quotes [Boolean] also return each quote in full
565
+ # signed form (+PointerPrepareResult#signed_quotes+)
566
+ # @return [PointerPrepareResult]
567
+ def pointer_prepare(owner, op, target: nil, kind: nil, recipient: nil, include_signed_quotes: false)
568
+ body = { owner: owner, op: op }
569
+ body[:target] = target unless target.nil?
570
+ body[:kind] = kind unless kind.nil?
571
+ body[:recipient] = recipient unless recipient.nil?
572
+ body[:include_signed_quotes] = true if include_signed_quotes
573
+ j = do_json(:post, "/v1/pointers/prepare", body)
574
+ PointerPrepareResult.new(
575
+ upload_id: j["upload_id"] || "",
576
+ op: j["op"] || "",
577
+ address: j["address"] || "",
578
+ state_id: j["state_id"] || "",
579
+ counter: Antd.parse_pointer_counter("counter", j["counter"]),
580
+ payment_type: j["payment_type"] || "",
581
+ payments: (j["payments"] || []).map do |p|
582
+ PaymentInfo.new(quote_hash: p["quote_hash"], rewards_address: p["rewards_address"], amount: p["amount"])
583
+ end,
584
+ total_amount: j["total_amount"] || "",
585
+ payment_vault_address: j["payment_vault_address"] || "",
586
+ payment_token_address: j["payment_token_address"] || "",
587
+ rpc_url: j["rpc_url"] || "",
588
+ signed_quotes: (j["signed_quotes"] || []).map do |q|
589
+ SignedQuoteEntry.new(
590
+ quote_hash: q["quote_hash"] || "",
591
+ quote: q["quote"] || "",
592
+ commitment_sidecar: presence(q["commitment_sidecar"])
593
+ )
594
+ end
595
+ )
596
+ end
597
+
598
+ # External signer: store a prepared pointer write once it is paid.
599
+ #
600
+ # A write that falls short after payment raises +CloseGroupShortfallError+
601
+ # with +retryable+ set: the daemon kept the paid state, so call this again
602
+ # with the same +upload_id+ (+tx_hashes+ is then ignored) to store it
603
+ # against the same payment. Bound that loop; the session expires with the
604
+ # daemon's one-hour pending TTL. Any other failure ends the session.
605
+ #
606
+ # @param upload_id [String] from +pointer_prepare+
607
+ # @param tx_hashes [Hash<String, String>] each +quote_hash+ from
608
+ # +payments+ to the +payForQuotes()+ transaction hash
609
+ # @return [PointerFinalizeResult]
610
+ def pointer_finalize(upload_id, tx_hashes)
611
+ j = do_json(:post, "/v1/pointers/finalize", { upload_id: upload_id, tx_hashes: tx_hashes })
612
+ PointerFinalizeResult.new(
613
+ address: j["address"] || "",
614
+ state_id: j["state_id"] || "",
615
+ counter: Antd.parse_pointer_counter("counter", j["counter"]),
616
+ finality: j["finality"].is_a?(Hash) ? parse_pointer_finality(j["finality"]) : nil
617
+ )
618
+ end
619
+
420
620
  private
421
621
 
622
+ # POST a pointer create / update. +kind+ is omitted when nil, so the
623
+ # daemon applies its default (chunk).
624
+ def pointer_write(path, owner, target, kind)
625
+ body = { owner: owner, target: target }
626
+ body[:kind] = kind unless kind.nil?
627
+ j = do_json(:post, path, body)
628
+ PointerWriteResult.new(
629
+ address: j["address"] || "",
630
+ state_id: j["state_id"] || "",
631
+ counter: Antd.parse_pointer_counter("counter", j["counter"])
632
+ )
633
+ end
634
+
635
+ # Parse a pointer finality JSON object. The daemon sends +null+ for every
636
+ # unset optional (+counter+, +state+, +majority+, +transferred_to+); each
637
+ # reads as nil.
638
+ def parse_pointer_finality(j)
639
+ PointerFinality.new(
640
+ address: j["address"] || "",
641
+ group: (j["group"] || 0).to_i,
642
+ answered: (j["answered"] || 0).to_i,
643
+ status: j["status"] || "",
644
+ counter: j["counter"].nil? ? nil : Antd.parse_pointer_counter("finality counter", j["counter"]),
645
+ state: j["state"].is_a?(Hash) ? parse_pointer_final_state(j["state"]) : nil,
646
+ states: (j["states"] || []).grep(Hash).map { |s| parse_pointer_final_state(s) },
647
+ majority: j["majority"].is_a?(Hash) ? parse_pointer_final_state(j["majority"]) : nil,
648
+ transferred_to: presence(j["transferred_to"])
649
+ )
650
+ end
651
+
652
+ def parse_pointer_final_state(j)
653
+ PointerFinalState.new(
654
+ state_id: j["state_id"] || "",
655
+ kind: j["kind"] || "",
656
+ kind_tag: (j["kind_tag"] || 0).to_i,
657
+ target: j["target"] || "",
658
+ holders: (j["holders"] || 0).to_i,
659
+ transferred_to: presence(j["transferred_to"])
660
+ )
661
+ end
662
+
663
+ # A wire string, or nil when absent, +null+ or empty.
664
+ def presence(value)
665
+ value.is_a?(String) && !value.empty? ? value : nil
666
+ end
667
+
422
668
  # Parse a /v1/upload/finalize JSON response into a FinalizeUploadResult.
423
669
  #
424
670
  # +data_map_address+ is populated only when prepare was called with
@@ -429,7 +675,8 @@ module Antd
429
675
  address: j["address"] || "",
430
676
  chunks_stored: (j["chunks_stored"] || 0).to_i,
431
677
  data_map: j["data_map"] || "",
432
- data_map_address: j["data_map_address"] || ""
678
+ data_map_address: j["data_map_address"] || "",
679
+ sha256: presence(j["sha256"])
433
680
  )
434
681
  end
435
682