webylib 0.2.3

Webcash HD wallet library — bearer e-cash with BIP32-style key derivation, SQLite storage, AES-256-GCM encryption, and full C FFI for cross-platform SDKs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# FFI Reference

Complete C API reference for `webylib`. All functions are exported with C linkage and can be called from any language that supports C FFI.

## Building

```bash
# Shared library (.so / .dylib / .dll) + static library (.a / .lib)
cargo build --release --features ffi

# Generate C header
cbindgen --crate webylib --output include/webylib.h
```

Output files in `target/release/`:
- Linux: `libwebylib.so`, `libwebylib.a`
- macOS: `libwebylib.dylib`, `libwebylib.a`
- Windows: `webylib.dll`, `webylib.lib`
- iOS: `libwebylib.a` (static only)
- Android: `libwebylib.so` (shared only)

## Conventions

- Every function returns `int32_t` (`0` = success, non-zero = error code)
- On failure, call `weby_last_error_message()` for a human-readable description
- Strings returned via `out_*` pointers must be freed with `weby_free_string()`
- Wallet handles must be freed with `weby_wallet_free()`
- The `weby_version()` pointer is static — do **not** free it
- The `weby_last_error_message()` pointer is thread-local, valid until next FFI call — do **not** free it

## Error Codes

```c
enum WebyErrorCode {
    WEBY_OK               =  0,
    WEBY_INVALID_INPUT     =  1,
    WEBY_DATABASE_ERROR    =  2,
    WEBY_CRYPTO_ERROR      =  3,
    WEBY_SERVER_ERROR      =  4,
    WEBY_INSUFFICIENT_FUNDS =  5,
    WEBY_NETWORK_ERROR     =  6,
    WEBY_AUTH_ERROR         =  7,
    WEBY_NOT_SUPPORTED     =  8,
    WEBY_UNKNOWN           = -1,
};
```

---

## Functions

### Lifecycle

#### `weby_wallet_open`

Open or create a wallet at the given filesystem path.

```c
int32_t weby_wallet_open(
    const char *path,         // null-terminated UTF-8 path
    WebyWallet **out_wallet   // receives wallet handle on success
);
```

#### `weby_wallet_open_with_seed`

Open or create a wallet with a caller-provided 32-byte seed. If the wallet already has a different master secret with existing transactions, returns `WEBY_INVALID_INPUT`.

```c
int32_t weby_wallet_open_with_seed(
    const char *path,         // null-terminated UTF-8 path
    const uint8_t *seed_ptr,  // pointer to 32-byte seed
    size_t seed_len,          // must be 32
    WebyWallet **out_wallet   // receives wallet handle on success
);
```

#### `weby_wallet_free`

Free a wallet handle. Safe to call with NULL (no-op).

```c
void weby_wallet_free(WebyWallet *wallet);
```

### Operations

#### `weby_wallet_balance`

Get the wallet balance as a decimal string (e.g., `"1.50000000"`).

```c
int32_t weby_wallet_balance(
    const WebyWallet *wallet,
    char **out_balance        // receives allocated string — free with weby_free_string()
);
```

#### `weby_wallet_insert`

Insert webcash into the wallet. Performs ownership transfer via the server (replace operation).

```c
int32_t weby_wallet_insert(
    const WebyWallet *wallet,
    const char *webcash_str   // e.g., "e1.00000000:secret:abcdef..."
);
```

#### `weby_wallet_pay`

Pay an amount from the wallet. Returns the payment webcash string for the recipient.

```c
int32_t weby_wallet_pay(
    const WebyWallet *wallet,
    const char *amount_str,   // decimal amount, e.g., "0.5"
    const char *memo,         // memo string (or NULL)
    char **out_webcash        // receives payment string — free with weby_free_string()
);
```

#### `weby_wallet_check`

Verify all wallet outputs against the server (detect spent outputs).

```c
int32_t weby_wallet_check(const WebyWallet *wallet);
```

#### `weby_wallet_merge`

Consolidate small outputs into fewer larger ones.

```c
int32_t weby_wallet_merge(
    const WebyWallet *wallet,
    uint32_t max_outputs,     // max outputs to merge per batch
    char **out_result         // receives summary string — free with weby_free_string()
);
```

#### `weby_wallet_recover`

Recover wallet contents from a master secret by scanning the server.

```c
int32_t weby_wallet_recover(
    const WebyWallet *wallet,
    const char *master_secret_hex,  // 64-character hex string
    uint32_t gap_limit,             // scan depth per chain (typically 20)
    char **out_result               // receives summary — free with weby_free_string()
);
```

### Inspection

#### `weby_wallet_stats`

Get wallet statistics as a JSON string.

```c
int32_t weby_wallet_stats(
    const WebyWallet *wallet,
    char **out_json           // receives JSON — free with weby_free_string()
);
```

Response format:
```json
{
  "total_webcash": 10,
  "unspent_webcash": 8,
  "spent_webcash": 5,
  "total_balance": "3.50000000"
}
```

#### `weby_wallet_export_snapshot`

Export full wallet state as a JSON string (for backup).

```c
int32_t weby_wallet_export_snapshot(
    const WebyWallet *wallet,
    char **out_json           // receives JSON — free with weby_free_string()
);
```

### Encryption

#### `weby_wallet_encrypt_seed`

Encrypt the wallet database with a password (Argon2 + AES-256-GCM).

```c
int32_t weby_wallet_encrypt_seed(
    const WebyWallet *wallet,
    const char *password      // null-terminated password
);
```

### Utilities

#### `weby_version`

Get the library version string. The returned pointer is **static** — do not free.

```c
const char *weby_version(void);
```

#### `weby_amount_parse`

Parse a decimal amount string into integer wats (1 webcash = 100,000,000 wats).

```c
int32_t weby_amount_parse(
    const char *amount_str,   // e.g., "1.5"
    int64_t *out_wats         // receives 150000000
);
```

#### `weby_amount_format`

Format integer wats as a decimal string.

```c
int32_t weby_amount_format(
    int64_t wats,             // e.g., 150000000
    char **out_str            // receives "1.5" — free with weby_free_string()
);
```

#### `weby_free_string`

Free a string previously returned by webylib. Safe to call with NULL (no-op).

```c
void weby_free_string(char *ptr);
```

#### `weby_last_error_message`

Get the last error message for the current thread. Returns NULL if no error. Do **not** free the returned pointer.

```c
const char *weby_last_error_message(void);
```

---

## Language Bindings

### Python (ctypes)

```python
import ctypes

lib = ctypes.CDLL("./target/release/libwebylib.dylib")  # or .so / .dll

# Define function signatures
lib.weby_wallet_open.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p)]
lib.weby_wallet_open.restype = ctypes.c_int32
lib.weby_wallet_balance.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_char_p)]
lib.weby_wallet_balance.restype = ctypes.c_int32
lib.weby_wallet_free.argtypes = [ctypes.c_void_p]
lib.weby_free_string.argtypes = [ctypes.c_char_p]
lib.weby_last_error_message.restype = ctypes.c_char_p

# Open wallet
wallet = ctypes.c_void_p()
rc = lib.weby_wallet_open(b"my_wallet.db", ctypes.byref(wallet))
if rc != 0:
    print(f"Error: {lib.weby_last_error_message().decode()}")
    exit(1)

# Get balance
balance = ctypes.c_char_p()
lib.weby_wallet_balance(wallet, ctypes.byref(balance))
print(f"Balance: {balance.value.decode()}")
lib.weby_free_string(balance)

# Clean up
lib.weby_wallet_free(wallet)
```

### Node.js (ffi-napi)

```javascript
const ffi = require('ffi-napi');
const ref = require('ref-napi');

const lib = ffi.Library('./target/release/libwebylib', {
  'weby_wallet_open':    ['int', ['string', ref.refType('pointer')]],
  'weby_wallet_balance': ['int', ['pointer', ref.refType('string')]],
  'weby_wallet_insert':  ['int', ['pointer', 'string']],
  'weby_wallet_pay':     ['int', ['pointer', 'string', 'string', ref.refType('string')]],
  'weby_wallet_free':    ['void', ['pointer']],
  'weby_free_string':    ['void', ['pointer']],
  'weby_last_error_message': ['string', []],
  'weby_version':        ['string', []],
});

// Open wallet
const walletPtr = ref.alloc('pointer');
const rc = lib.weby_wallet_open('my_wallet.db', walletPtr);
if (rc !== 0) throw new Error(lib.weby_last_error_message());
const wallet = walletPtr.deref();

// Get balance
const balancePtr = ref.alloc('string');
lib.weby_wallet_balance(wallet, balancePtr);
console.log(`Balance: ${balancePtr.deref()}`);

lib.weby_wallet_free(wallet);
```

### C# / .NET (P/Invoke)

```csharp
using System;
using System.Runtime.InteropServices;

public static class Webylib
{
    const string LIB = "webylib";

    [DllImport(LIB)] public static extern int weby_wallet_open(string path, out IntPtr wallet);
    [DllImport(LIB)] public static extern int weby_wallet_balance(IntPtr wallet, out IntPtr balance);
    [DllImport(LIB)] public static extern int weby_wallet_insert(IntPtr wallet, string webcash);
    [DllImport(LIB)] public static extern int weby_wallet_pay(IntPtr wallet, string amount, string memo, out IntPtr webcash);
    [DllImport(LIB)] public static extern int weby_wallet_check(IntPtr wallet);
    [DllImport(LIB)] public static extern void weby_wallet_free(IntPtr wallet);
    [DllImport(LIB)] public static extern void weby_free_string(IntPtr str);
    [DllImport(LIB)] public static extern IntPtr weby_last_error_message();
    [DllImport(LIB)] public static extern IntPtr weby_version();
}

// Usage:
IntPtr wallet;
int rc = Webylib.weby_wallet_open("my_wallet.db", out wallet);
if (rc != 0) {
    Console.WriteLine($"Error: {Marshal.PtrToStringAnsi(Webylib.weby_last_error_message())}");
    return;
}

IntPtr balancePtr;
Webylib.weby_wallet_balance(wallet, out balancePtr);
Console.WriteLine($"Balance: {Marshal.PtrToStringAnsi(balancePtr)}");
Webylib.weby_free_string(balancePtr);

Webylib.weby_wallet_free(wallet);
```

### Go (cgo)

```go
package main

/*
#cgo LDFLAGS: -L./target/release -lwebylib -lm -ldl -lpthread
#include <stdlib.h>

extern int weby_wallet_open(const char *path, void **out_wallet);
extern int weby_wallet_balance(const void *wallet, char **out_balance);
extern void weby_wallet_free(void *wallet);
extern void weby_free_string(char *ptr);
extern const char *weby_last_error_message();
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    var wallet unsafe.Pointer
    path := C.CString("my_wallet.db")
    defer C.free(unsafe.Pointer(path))

    rc := C.weby_wallet_open(path, &wallet)
    if rc != 0 {
        fmt.Printf("Error: %s\n", C.GoString(C.weby_last_error_message()))
        return
    }
    defer C.weby_wallet_free(wallet)

    var balance *C.char
    C.weby_wallet_balance(wallet, &balance)
    fmt.Printf("Balance: %s\n", C.GoString(balance))
    C.weby_free_string(balance)
}
```

### Swift

```swift
import Foundation

// Link against libwebylib.a (static) or libwebylib.dylib (dynamic)
// Add bridging header with webylib.h

var wallet: OpaquePointer?
let rc = weby_wallet_open("my_wallet.db", &wallet)
guard rc == 0, let w = wallet else {
    if let msg = weby_last_error_message() {
        print("Error: \(String(cString: msg))")
    }
    exit(1)
}

var balance: UnsafeMutablePointer<CChar>?
weby_wallet_balance(w, &balance)
if let b = balance {
    print("Balance: \(String(cString: b))")
    weby_free_string(b)
}

weby_wallet_free(w)
```

### Java (JNI / JNA)

```java
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;

public interface Webylib extends Library {
    Webylib INSTANCE = Native.load("webylib", Webylib.class);

    int weby_wallet_open(String path, PointerByReference outWallet);
    int weby_wallet_balance(Pointer wallet, PointerByReference outBalance);
    int weby_wallet_insert(Pointer wallet, String webcash);
    void weby_wallet_free(Pointer wallet);
    void weby_free_string(Pointer ptr);
    String weby_last_error_message();
    String weby_version();
}

// Usage:
PointerByReference walletRef = new PointerByReference();
int rc = Webylib.INSTANCE.weby_wallet_open("my_wallet.db", walletRef);
if (rc != 0) {
    System.err.println("Error: " + Webylib.INSTANCE.weby_last_error_message());
    return;
}
Pointer wallet = walletRef.getValue();

PointerByReference balanceRef = new PointerByReference();
Webylib.INSTANCE.weby_wallet_balance(wallet, balanceRef);
System.out.println("Balance: " + balanceRef.getValue().getString(0));
Webylib.INSTANCE.weby_free_string(balanceRef.getValue());

Webylib.INSTANCE.weby_wallet_free(wallet);
```

### Kotlin (JNA)

```kotlin
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.ptr.PointerByReference

interface Webylib : Library {
    fun weby_wallet_open(path: String, outWallet: PointerByReference): Int
    fun weby_wallet_balance(wallet: Pointer, outBalance: PointerByReference): Int
    fun weby_wallet_insert(wallet: Pointer, webcash: String): Int
    fun weby_wallet_free(wallet: Pointer)
    fun weby_free_string(ptr: Pointer)
    fun weby_last_error_message(): String?
    fun weby_version(): String

    companion object {
        val INSTANCE: Webylib = Native.load("webylib", Webylib::class.java)
    }
}

fun main() {
    val walletRef = PointerByReference()
    val rc = Webylib.INSTANCE.weby_wallet_open("my_wallet.db", walletRef)
    check(rc == 0) { "Error: ${Webylib.INSTANCE.weby_last_error_message()}" }
    val wallet = walletRef.value

    val balanceRef = PointerByReference()
    Webylib.INSTANCE.weby_wallet_balance(wallet, balanceRef)
    println("Balance: ${balanceRef.value.getString(0)}")
    Webylib.INSTANCE.weby_free_string(balanceRef.value)

    Webylib.INSTANCE.weby_wallet_free(wallet)
}
```