firewood-ffi 0.3.1

C FFI bindings for Firewood, an embedded key-value store optimized for blockchain state.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
// Copyright (C) 2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE.md for licensing terms.

// HINT WHEN REFERENCING TYPES OUTSIDE THIS LIBRARY:
// - Anything that is outside the crate must be included as a `type` alias (not just
//   a `use`) in order for cbindgen to generate an opaque forward declaration. The type
//   alias can have a doc comment which will be included in the generated header file.
// - The value must be boxed, or otherwise used via a pointer. This is because only
//   a forward declaration is generated and callers will be unable to instantiate the
//   type without a complete definition.

#![doc = include_str!("../README.md")]
#![expect(
    unsafe_code,
    reason = "This is an FFI library, so unsafe code is expected."
)]
#![cfg_attr(
    not(target_pointer_width = "64"),
    forbid(
        clippy::cast_possible_truncation,
        reason = "non-64 bit target likely to cause issues during u64 to usize conversions"
    )
)]

mod arc_cache;
mod handle;
mod iterator;
mod logging;
mod metrics;
mod proofs;
mod proposal;
mod reconstructed;
mod registry;
#[cfg(feature = "block-replay")]
mod replay;
mod revision;
mod value;

use firewood::api::DbView;
use firewood_metrics::set_metrics_context;

pub use crate::handle::*;
pub use crate::iterator::*;
pub use crate::logging::*;
use crate::metrics::MetricsContextExt;
pub use crate::proofs::*;
pub use crate::proposal::*;
pub use crate::reconstructed::*;
pub use crate::revision::*;
pub use crate::value::*;

#[global_allocator]
#[doc(hidden)]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

/// Invokes a closure and returns the result as a [`CResult`].
///
/// If the closure panics, it will return [`CResult::from_panic`] with the panic
/// information.
#[inline]
fn invoke<T: CResult, V: Into<T>>(once: impl FnOnce() -> V) -> T {
    #[cfg(panic = "unwind")]
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(once)) {
        Ok(result) => result.into(),
        Err(panic) => T::from_panic(panic),
    }

    #[cfg(not(panic = "unwind"))]
    {
        once().into()
    }
}

/// Invokes a closure with context from the handle.
#[inline]
fn invoke_with_handle<H: MetricsContextExt, T: NullHandleResult, V: Into<T>>(
    handle: Option<H>,
    once: impl FnOnce(H) -> V,
) -> T {
    match handle {
        Some(handle) => {
            let _guard = set_metrics_context(handle.metrics_context());
            invoke(move || once(handle))
        }
        None => T::null_handle_pointer_error(),
    }
}

/// Gets the value associated with the given key from the database for the
/// latest revision.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::RevisionNotFound`] if no revision was found for the root
///   (i.e., there is no current root).
/// - [`ValueResult::None`] if the key was not found.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * ensure that `key` is valid for [`BorrowedBytes`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error or value.
///
/// [`BorrowedBytes`]: crate::value::BorrowedBytes
#[unsafe(no_mangle)]
pub extern "C" fn fwd_get_latest(db: Option<&DatabaseHandle>, key: BorrowedBytes) -> ValueResult {
    #[cfg(feature = "block-replay")]
    if db.is_some() {
        replay::record_get_latest(key);
    }

    invoke_with_handle(db, move |db| db.get_latest(key))
}

/// Returns an iterator optionally starting from a key in the provided revision.
///
/// # Arguments
///
/// * `revision` - The revision handle returned by [`fwd_get_revision`].
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`IteratorResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`IteratorResult::Ok`] if the iterator was created, with the iterator handle.
/// - [`IteratorResult::Err`] if an error occurred while creating the iterator.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`]
/// * ensure that `key` is a valid [`BorrowedBytes`]
/// * call [`fwd_free_iterator`] to free the memory associated with the iterator.
///
#[unsafe(no_mangle)]
pub extern "C" fn fwd_iter_on_revision<'view>(
    revision: Option<&'view RevisionHandle<'_>>,
    key: BorrowedBytes,
) -> IteratorResult<'view> {
    invoke_with_handle(revision, move |rev| rev.iter_from(Some(key.as_slice())))
}

/// Returns an iterator on the provided proposal optionally starting from a key
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
///   [`fwd_propose_on_proposal`].
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`IteratorResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`IteratorResult::Ok`] if the iterator was created, with the iterator handle.
/// - [`IteratorResult::Err`] if an error occurred while creating the iterator.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `key` is a valid for [`BorrowedBytes`]
/// * call [`fwd_free_iterator`] to free the memory associated with the iterator.
///
#[unsafe(no_mangle)]
pub extern "C" fn fwd_iter_on_proposal<'p>(
    handle: Option<&'p ProposalHandle<'_>>,
    key: BorrowedBytes,
) -> IteratorResult<'p> {
    invoke_with_handle(handle, move |p| p.iter_from(Some(key.as_slice())))
}

/// Returns an iterator on the provided reconstructed view optionally starting from a key.
///
/// # Arguments
///
/// * `handle` - The reconstructed handle returned by [`fwd_reconstruct_on_revision`] or
///   [`fwd_reconstruct_on_reconstructed`].
/// * `key` - The key to start iterating from as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`IteratorResult::NullHandlePointer`] if the provided handle is null.
/// - [`IteratorResult::Ok`] if the iterator was created, with the iterator handle.
/// - [`IteratorResult::Err`] if an error occurred while creating the iterator.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ReconstructedHandle`]
/// * ensure that `key` is a valid [`BorrowedBytes`]
/// * call [`fwd_free_iterator`] to free the memory associated with the iterator.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_iter_on_reconstructed<'p>(
    handle: Option<&'p ReconstructedHandle<'_>>,
    key: BorrowedBytes,
) -> IteratorResult<'p> {
    invoke_with_handle(handle, move |h| h.iter_from(Some(key.as_slice())))
}

/// Retrieves the next item from the iterator.
///
/// # Arguments
///
/// * `handle` - The iterator handle returned by [`fwd_iter_on_revision`] or
///   [`fwd_iter_on_proposal`].
///
/// # Returns
///
/// - [`KeyValueResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`KeyValueResult::None`] if the iterator is exhausted (no remaining values). Once returned,
///   subsequent calls will continue returning [`KeyValueResult::None`]. You may still call this
///   safely, but freeing the iterator with [`fwd_free_iterator`] is recommended.
/// - [`KeyValueResult::Some`] if the next item on iterator was retrieved, with the associated
///   key value pair.
/// - [`KeyValueResult::Err`] if an I/O error occurred while retrieving the next item. Most
///   iterator errors are non-reentrant. Once returned, the iterator should be considered
///   invalid and must be freed with [`fwd_free_iterator`].
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`IteratorHandle`].
/// * call [`fwd_free_owned_kv_pair`] on returned [`OwnedKeyValuePair`]
///   to free the memory associated with the returned value.
///
#[unsafe(no_mangle)]
pub extern "C" fn fwd_iter_next(handle: Option<&mut IteratorHandle<'_>>) -> KeyValueResult {
    invoke_with_handle(handle, Iterator::next)
}

/// Retrieves the next batch of items from the iterator.
///
/// # Arguments
///
/// * `handle` - The iterator handle returned by [`fwd_iter_on_revision`] or
///   [`fwd_iter_on_proposal`].
///
/// # Returns
///
/// - [`KeyValueBatchResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`KeyValueBatchResult::Some`] with up to `n` key/value pairs. If the iterator is
///   exhausted, this may be fewer than `n`, including zero items.
/// - [`KeyValueBatchResult::Err`] if an I/O error occurred while retrieving items. Most
///   iterator errors are non-reentrant. Once returned, the iterator should be considered
///   invalid and must be freed with [`fwd_free_iterator`].
///
/// Once an empty batch or items fewer than `n` is returned (iterator exhausted), subsequent calls
/// will continue returning empty batches. You may still call this safely, but freeing the
/// iterator with [`fwd_free_iterator`] is recommended.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`IteratorHandle`].
/// * call [`fwd_free_owned_key_value_batch`] on the returned batch to free any allocated memory.
///
#[unsafe(no_mangle)]
pub extern "C" fn fwd_iter_next_n(
    handle: Option<&mut IteratorHandle<'_>>,
    n: usize,
) -> KeyValueBatchResult {
    invoke_with_handle(handle, |it| it.iter_next_n(n))
}

/// Consumes the [`IteratorHandle`], destroys the iterator, and frees the memory.
///
/// # Arguments
///
/// * `iterator` - A pointer to a [`IteratorHandle`] previously returned from a
///   function from this library.
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`VoidResult::Ok`] if the iterator was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `iterator` is not null and that it points to
/// a valid [`IteratorHandle`] previously returned by a function from this library.
///
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_iterator(iterator: Option<Box<IteratorHandle<'_>>>) -> VoidResult {
    invoke_with_handle(iterator, drop)
}

/// Gets a handle to the revision identified by the provided root hash.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`].
/// * `root` - The hash of the revision as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`RevisionResult::NullHandlePointer`] if the provided database handle is null.
/// - [`RevisionResult::Ok`] containing a [`RevisionHandle`] and root hash if the revision exists.
/// - [`RevisionResult::Err`] if the revision cannot be fetched or the root hash is invalid.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * ensure that `root` is valid for [`BorrowedBytes`].
/// * call [`fwd_free_revision`] to free the returned handle when it is no longer needed.
/// * ensure that the [`DatabaseHandle`] remains valid (not closed via [`fwd_close_db`])
///   for as long as the returned [`RevisionHandle`] (and any derived [`ReconstructedHandle`])
///   is in use.
///
/// [`BorrowedBytes`]: crate::value::BorrowedBytes
/// [`RevisionHandle`]: crate::revision::RevisionHandle
#[unsafe(no_mangle)]
pub extern "C" fn fwd_get_revision(
    db: Option<&DatabaseHandle>,
    root: HashKey,
) -> RevisionResult<'_> {
    invoke_with_handle(db, move |db| db.get_revision(root.into()))
}

/// Gets the value associated with the given key from the provided revision handle.
///
/// # Arguments
///
/// * `revision` - The revision handle returned by [`fwd_get_revision`].
/// * `key` - The key to look up as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`ValueResult::None`] if the key was not found in the revision.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`].
/// * ensure that `key` is valid for [`BorrowedBytes`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the [`OwnedBytes`]
///   returned in the result.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_get_from_revision(
    revision: Option<&RevisionHandle<'_>>,
    key: BorrowedBytes,
) -> ValueResult {
    invoke_with_handle(revision, move |rev| rev.val(key))
}

/// Consumes the [`RevisionHandle`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `revision` - A pointer to a [`RevisionHandle`] previously returned by
///   [`fwd_get_revision`].
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`VoidResult::Ok`] if the revision handle was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the revision handle is valid and is not used again after
/// this function is called.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_revision(revision: Option<Box<RevisionHandle<'_>>>) -> VoidResult {
    invoke_with_handle(revision, drop)
}

/// Gets the value associated with the given key from the proposal provided.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
///   [`fwd_propose_on_proposal`].
/// * `key` - The key to look up, as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::None`] if the key was not found.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `key` is valid for [`BorrowedBytes`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated [`OwnedBytes`]
///   returned in the result.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_get_from_proposal(
    handle: Option<&ProposalHandle<'_>>,
    key: BorrowedBytes,
) -> ValueResult {
    #[cfg(feature = "block-replay")]
    replay::record_get_from_proposal(handle, key);

    invoke_with_handle(handle, move |handle| handle.val(key))
}

/// Gets the value associated with the given key from the reconstructed view provided.
///
/// # Arguments
///
/// * `handle` - The reconstructed handle returned by [`fwd_reconstruct_on_revision`] or
///   [`fwd_reconstruct_on_reconstructed`].
/// * `key` - The key to look up as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided handle is null.
/// - [`ValueResult::None`] if the key was not found in the reconstructed view.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ReconstructedHandle`].
/// * ensure that `key` is valid for [`BorrowedBytes`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the [`OwnedBytes`]
///   returned in the result.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_get_from_reconstructed(
    handle: Option<&ReconstructedHandle<'_>>,
    key: BorrowedBytes,
) -> ValueResult {
    invoke_with_handle(handle, move |handle| handle.val(key))
}

/// Puts the given key-value pairs into the database.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `values` - A [`BorrowedBatchOps`] containing the batch operations to apply.
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the commit resulted in an empty database.
/// - [`HashResult::Some`] if the commit was successful, containing the new root hash.
/// - [`HashResult::Err`] if an error occurred while committing the batch.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * ensure that `values` is valid for [`BorrowedBatchOps`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error ([`HashKey`] does not need to be freed as it is returned by
///   value).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_batch(
    db: Option<&DatabaseHandle>,
    values: BorrowedBatchOps<'_>,
) -> HashResult {
    #[cfg(feature = "block-replay")]
    if db.is_some() {
        replay::record_batch(values);
    }

    invoke_with_handle(db, move |db| db.create_batch(values))
}

/// Proposes a batch of operations to the database.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `values` - A [`BorrowedBatchOps`] containing the batch operations to apply.
///
/// # Returns
///
/// - [`ProposalResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ProposalResult::Ok`] if the proposal was created, with the proposal handle
///   and calculated root hash.
/// - [`ProposalResult::Err`] if an error occurred while creating the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * ensure that `values` is valid for [`BorrowedBatchOps`]
/// * call [`fwd_commit_proposal`] or [`fwd_free_proposal`] to free the memory
///   associated with the proposal. And, the caller must ensure this is done
///   before calling [`fwd_close_db`] to avoid memory leaks or undefined behavior.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_propose_on_db<'db>(
    db: Option<&'db DatabaseHandle>,
    values: BorrowedBatchOps<'_>,
) -> ProposalResult<'db> {
    let result = invoke_with_handle(db, move |db| db.create_proposal_handle(values));

    #[cfg(feature = "block-replay")]
    if db.is_some() {
        replay::record_propose_on_db(&result, values);
    }

    result
}

/// Proposes a batch of operations to the database on top of an existing proposal.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
///   [`fwd_propose_on_proposal`].
/// * `values` - A [`BorrowedBatchOps`] containing the batch operations to apply.
///
/// # Returns
///
/// - [`ProposalResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ProposalResult::Ok`] if the proposal was created, with the proposal handle
///   and calculated root hash.
/// - [`ProposalResult::Err`] if an error occurred while creating the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `values` is valid for [`BorrowedBatchOps`]
/// * call [`fwd_commit_proposal`] or [`fwd_free_proposal`] to free the memory
///   associated with the proposal. And, the caller must ensure this is done
///   before calling [`fwd_close_db`] to avoid memory leaks or undefined behavior.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_propose_on_proposal<'db>(
    handle: Option<&ProposalHandle<'db>>,
    values: BorrowedBatchOps<'_>,
) -> ProposalResult<'db> {
    let result = invoke_with_handle(handle, move |p| p.create_proposal_handle(values));

    #[cfg(feature = "block-replay")]
    replay::record_propose_on_proposal(handle, &result, values);

    result
}

/// Reconstructs a batch of operations on top of a historical revision.
///
/// # Arguments
///
/// * `handle` - The revision handle returned by [`fwd_get_revision`].
/// * `values` - A [`BorrowedBatchOps`] containing the batch operations to apply.
///
/// # Returns
///
/// - [`ReconstructedResult::NullHandlePointer`] if the provided handle is null.
/// - [`ReconstructedResult::Ok`] if reconstruction succeeded, with a [`ReconstructedHandle`].
/// - [`ReconstructedResult::Err`] if reconstruction failed (e.g., the revision is not historical).
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`RevisionHandle`].
/// * ensure that `values` is valid for [`BorrowedBatchOps`].
/// * call [`fwd_free_reconstructed`] to free the returned handle when it is no longer needed.
/// * ensure that the underlying [`DatabaseHandle`] remains valid (not closed via [`fwd_close_db`])
///   for as long as the returned [`ReconstructedHandle`] is in use.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_reconstruct_on_revision<'db>(
    handle: Option<&'db RevisionHandle<'db>>,
    values: BorrowedBatchOps<'_>,
) -> ReconstructedResult<'db> {
    invoke_with_handle(handle, move |h| h.reconstruct(values))
}

/// Reconstructs a batch of operations on top of an existing reconstructed view.
///
/// This function consumes the previous reconstructed handle.
///
/// # Arguments
///
/// * `handle` - The reconstructed handle returned by a previous call to
///   [`fwd_reconstruct_on_revision`] or [`fwd_reconstruct_on_reconstructed`].
/// * `values` - A [`BorrowedBatchOps`] containing the batch operations to apply.
///
/// # Returns
///
/// - [`ReconstructedResult::NullHandlePointer`] if the provided handle is null.
/// - [`ReconstructedResult::Ok`] if reconstruction succeeded, with a new [`ReconstructedHandle`].
/// - [`ReconstructedResult::Err`] if reconstruction failed.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ReconstructedHandle`].
/// * ensure that `values` is valid for [`BorrowedBatchOps`].
/// * call [`fwd_free_reconstructed`] to free the returned handle when it is no longer needed.
/// * ensure that the underlying [`DatabaseHandle`] remains valid (not closed via [`fwd_close_db`])
///   for as long as the returned [`ReconstructedHandle`] is in use.
/// * not use the consumed `handle` after this call.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_reconstruct_on_reconstructed<'db>(
    handle: Option<Box<ReconstructedHandle<'db>>>,
    values: BorrowedBatchOps<'_>,
) -> ReconstructedResult<'db> {
    invoke_with_handle(handle, move |h| h.reconstruct(values))
}

/// Commits a proposal to the database.
///
/// This function will consume the proposal regardless of whether the commit
/// is successful.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
///   [`fwd_propose_on_proposal`].
///
/// # Returns
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the commit resulted in an empty database.
/// - [`HashResult::Some`] if the commit was successful, containing the new root hash.
/// - [`HashResult::Err`] if an error occurred while committing the batch.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `handle` is not used again after this function is called.
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error ([`HashKey`] does not need to be freed as it is returned
///   by value).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_commit_proposal(proposal: Option<Box<ProposalHandle<'_>>>) -> HashResult {
    #[cfg(feature = "block-replay")]
    let proposal_ptr = proposal.as_ref().map(|h| std::ptr::from_ref(&**h));

    let result = invoke_with_handle(proposal, move |proposal| proposal.commit_proposal());

    #[cfg(feature = "block-replay")]
    replay::record_commit(proposal_ptr, &result);

    result
}

/// Consumes the [`ProposalHandle`], cancels the proposal, and frees the memory.
///
/// # Arguments
///
/// * `proposal` - A pointer to a [`ProposalHandle`] previously returned from a
///   function from this library.
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`VoidResult::Ok`] if the proposal was successfully cancelled and freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `proposal` is not null and that it points to
/// a valid [`ProposalHandle`] previously returned by a function from this library.
///
/// The caller must ensure that the proposal was not committed. [`fwd_commit_proposal`]
/// will consume the proposal automatically.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_proposal(proposal: Option<Box<ProposalHandle<'_>>>) -> VoidResult {
    invoke_with_handle(proposal, drop)
}

/// Consumes the [`ReconstructedHandle`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `reconstructed` - A pointer to a [`ReconstructedHandle`] previously returned by
///   [`fwd_reconstruct_on_revision`] or [`fwd_reconstruct_on_reconstructed`].
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided handle is null.
/// - [`VoidResult::Ok`] if the handle was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must:
/// * ensure that `reconstructed` is a valid pointer to a [`ReconstructedHandle`].
/// * not use `reconstructed` after this function is called.
/// * free all reconstructed handles before closing the database with [`fwd_close_db`].
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_reconstructed(
    reconstructed: Option<Box<ReconstructedHandle<'_>>>,
) -> VoidResult {
    invoke_with_handle(reconstructed, drop)
}

/// Get the root hash of the reconstructed view.
///
/// # Arguments
///
/// * `reconstructed` - The reconstructed handle returned by reconstruction APIs.
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided handle is null.
/// - [`HashResult::None`] if the reconstructed view is empty.
/// - [`HashResult::Some`] with the root hash of the reconstructed view.
///
/// # Safety
///
/// * ensure that `reconstructed` is a valid pointer to a [`ReconstructedHandle`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error ([`HashKey`] does not need to be freed as it is returned
///   by value).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_reconstructed_root_hash(
    reconstructed: Option<&ReconstructedHandle<'_>>,
) -> HashResult {
    invoke_with_handle(reconstructed, firewood::api::DbView::root_hash)
}

/// Get the root hash of the latest version of the database
///
/// # Argument
///
/// * `db` - The database handle returned by [`fwd_open_db`]
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the database is empty.
/// - [`HashResult::Some`] with the root hash of the database.
///
/// # Safety
///
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error ([`HashKey`] does not need to be freed as it is returned
///   by value).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_root_hash(db: Option<&DatabaseHandle>) -> HashResult {
    invoke_with_handle(db, DatabaseHandle::current_root_hash)
}

/// Start metrics recorder for this process.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the recorder was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_metrics() -> VoidResult {
    invoke(metrics::setup_metrics)
}

/// Start metrics recorder and exporter for this process.
///
/// # Arguments
///
/// * `metrics_port` - the port where metrics will be exposed at
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the recorder was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization.
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error (if any).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_metrics_with_exporter(metrics_port: u16) -> VoidResult {
    invoke(move || metrics::setup_metrics_with_exporter(metrics_port))
}

/// Gather latest metrics for this process.
///
/// # Returns
///
/// - [`ValueResult::None`] if the gathered metrics resulted in an empty string.
/// - [`ValueResult::Some`] the gathered metrics as an [`OwnedBytes`] (with
///   guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error or value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_gather() -> ValueResult {
    invoke(metrics::gather_metrics)
}

/// Open a database with the given arguments.
///
/// # Arguments
///
/// See [`DatabaseHandleArgs`].
///
/// # Returns
///
/// - [`HandleResult::Ok`] with the database handle if successful.
/// - [`HandleResult::Err`] if an error occurs while opening the database.
///
/// # Safety
///
/// The caller must:
/// - ensure that the database is freed with [`fwd_close_db`] when no longer needed.
/// - ensure that the database handle is freed only after freeing or committing
///   all proposals created on it.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_open_db(args: DatabaseHandleArgs) -> HandleResult {
    invoke(move || DatabaseHandle::new(args))
}

/// Start logs for this process.
///
/// # Arguments
///
/// See [`LogArgs`].
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the recorder was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization.
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned error (if any).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_logs(args: LogArgs) -> VoidResult {
    invoke(move || args.start_logging())
}

/// Close and free the memory for a database handle
///
/// This also stops the background persistence thread.
///
/// # Arguments
///
/// * `db` - The database handle to close, previously returned from a call to [`fwd_open_db`].
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided database handle is null.
/// - [`VoidResult::Ok`] if the database handle was successfully closed and freed.
/// - [`VoidResult::Err`] if the background persistence worker thread panics while
///   closing the database handle or if the background persistence worker thread
///   errored.
///
/// # Safety
///
/// Callers must ensure that:
///
/// - `db` is a valid pointer to a [`DatabaseHandle`] returned by [`fwd_open_db`].
/// - There are no handles to any open proposals. If so, they must be freed first
///   using [`fwd_free_proposal`].
/// - Freeing the database handle does not free outstanding [`RevisionHandle`]s
///   returned by [`fwd_get_revision`]. To prevent leaks, free them separately
///   with [`fwd_free_revision`].
/// - The database handle is not used after this function is called.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_close_db(db: Option<Box<DatabaseHandle>>) -> VoidResult {
    #[cfg(feature = "block-replay")]
    let _ = replay::flush_to_disk();

    invoke_with_handle(db, |db| db.close())
}

/// Flushes buffered block replay operations to disk.
///
/// This function is only meaningful when the `block-replay` feature is enabled
/// and the `FIREWOOD_BLOCK_REPLAY_PATH` environment variable is set. Otherwise,
/// it is a no-op.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the flush succeeded or was a no-op.
/// - [`VoidResult::Err`] if an I/O error occurred during the flush.
#[unsafe(no_mangle)]
#[allow(clippy::missing_const_for_fn)] // Can't be const when block-replay is enabled
pub extern "C" fn fwd_block_replay_flush() -> VoidResult {
    #[cfg(feature = "block-replay")]
    {
        invoke(replay::flush_to_disk)
    }

    #[cfg(not(feature = "block-replay"))]
    {
        VoidResult::Ok
    }
}

/// Consumes the [`OwnedBytes`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `bytes` - The [`OwnedBytes`] struct to free, previously returned from any
///   function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `bytes` struct is valid and that the memory
/// it points to is uniquely owned by this object. However, if `bytes.ptr` is null,
/// this function does nothing.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_owned_bytes(bytes: OwnedBytes) -> VoidResult {
    invoke(move || drop(bytes))
}

/// Consumes the [`OwnedKeyValueBatch`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `batch` - The [`OwnedKeyValueBatch`] struct to free, previously returned from any
///   function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `batch` struct is valid and that the memory
/// it points to is uniquely owned by this object. However, if `batch.ptr` is null,
/// this function does nothing.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_owned_key_value_batch(batch: OwnedKeyValueBatch) -> VoidResult {
    invoke(move || drop(batch))
}

/// Consumes the [`OwnedKeyValuePair`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `kv` - The [`OwnedKeyValuePair`] struct to free, previously returned from any
///   function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `kv` struct is valid.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_free_owned_kv_pair(kv: OwnedKeyValuePair) -> VoidResult {
    invoke(move || drop(kv))
}

/// Dumps the Trie structure of the latest revision of the database to a DOT
/// (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
///   guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the database.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_db_dump(db: Option<&DatabaseHandle>) -> ValueResult {
    invoke_with_handle(db, handle::DatabaseHandle::dump_to_string)
}

/// Dumps the Trie structure of a revision to a DOT (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `revision` - A pointer to a [`RevisionHandle`] previously returned by
///   [`fwd_get_revision`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
///   guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the revision.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_revision_dump(revision: Option<&RevisionHandle<'_>>) -> ValueResult {
    invoke_with_handle(revision, firewood::api::DbView::dump_to_string)
}

/// Dumps the Trie structure of a proposal to a DOT (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `proposal` - The proposal handle returned by [`fwd_propose_on_db`] or
///   [`fwd_propose_on_proposal`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
///   guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `proposal` is a valid pointer to a [`ProposalHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_proposal_dump(proposal: Option<&ProposalHandle>) -> ValueResult {
    invoke_with_handle(proposal, firewood::api::DbView::dump_to_string)
}

/// Dumps the Trie structure of a reconstructed view to a DOT (Graphviz) format string
/// for debugging.
///
/// # Arguments
///
/// * `reconstructed` - The reconstructed handle returned by [`fwd_reconstruct_on_revision`]
///   or [`fwd_reconstruct_on_reconstructed`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
///   guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the reconstructed view.
///
/// # Safety
///
/// The caller must:
/// * ensure that `reconstructed` is a valid pointer to a [`ReconstructedHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
///   returned value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_reconstructed_dump(
    reconstructed: Option<&ReconstructedHandle<'_>>,
) -> ValueResult {
    invoke_with_handle(reconstructed, firewood::api::DbView::dump_to_string)
}