-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathSTAmount.cpp
More file actions
1770 lines (1524 loc) · 47.9 KB
/
STAmount.cpp
File metadata and controls
1770 lines (1524 loc) · 47.9 KB
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
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <xrpl/basics/LocalValue.h>
#include <xrpl/basics/Log.h>
#include <xrpl/basics/Number.h>
#include <xrpl/basics/base_uint.h>
#include <xrpl/basics/contract.h>
#include <xrpl/basics/safe_cast.h>
#include <xrpl/beast/core/LexicalCast.h>
#include <xrpl/beast/utility/Zero.h>
#include <xrpl/beast/utility/instrumentation.h>
#include <xrpl/json/json_forwards.h>
#include <xrpl/json/json_value.h>
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/Asset.h>
#include <xrpl/protocol/IOUAmount.h>
#include <xrpl/protocol/Issue.h>
#include <xrpl/protocol/MPTAmount.h>
#include <xrpl/protocol/MPTIssue.h>
#include <xrpl/protocol/Protocol.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/STBase.h>
#include <xrpl/protocol/STNumber.h>
#include <xrpl/protocol/Serializer.h>
#include <xrpl/protocol/SystemParameters.h>
#include <xrpl/protocol/UintTypes.h>
#include <xrpl/protocol/XRPAmount.h>
#include <xrpl/protocol/jss.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/multiprecision/detail/default_ops.hpp>
#include <boost/multiprecision/fwd.hpp>
#include <boost/regex/v5/regbase.hpp>
#include <boost/regex/v5/regex.hpp>
#include <boost/regex/v5/regex_fwd.hpp>
#include <boost/regex/v5/regex_match.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <iterator>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace ripple {
namespace {
// Use a static inside a function to help prevent order-of-initialzation issues
LocalValue<bool>&
getStaticSTAmountCanonicalizeSwitchover()
{
static LocalValue<bool> r{true};
return r;
}
} // namespace
bool
getSTAmountCanonicalizeSwitchover()
{
return *getStaticSTAmountCanonicalizeSwitchover();
}
void
setSTAmountCanonicalizeSwitchover(bool v)
{
*getStaticSTAmountCanonicalizeSwitchover() = v;
}
static std::uint64_t const tenTo14 = 100000000000000ull;
static std::uint64_t const tenTo14m1 = tenTo14 - 1;
static std::uint64_t const tenTo17 = tenTo14 * 1000;
//------------------------------------------------------------------------------
static std::int64_t
getInt64Value(STAmount const& amount, bool valid, char const* error)
{
if (!valid)
Throw<std::runtime_error>(error);
XRPL_ASSERT(
amount.exponent() == 0, "ripple::getInt64Value : exponent is zero");
auto ret = static_cast<std::int64_t>(amount.mantissa());
XRPL_ASSERT(
static_cast<std::uint64_t>(ret) == amount.mantissa(),
"ripple::getInt64Value : mantissa must roundtrip");
if (amount.negative())
ret = -ret;
return ret;
}
static std::int64_t
getSNValue(STAmount const& amount)
{
return getInt64Value(amount, amount.native(), "amount is not native!");
}
static std::int64_t
getMPTValue(STAmount const& amount)
{
return getInt64Value(
amount, amount.holds<MPTIssue>(), "amount is not MPT!");
}
static bool
areComparable(STAmount const& v1, STAmount const& v2)
{
if (v1.holds<Issue>() && v2.holds<Issue>())
return v1.native() == v2.native() &&
v1.get<Issue>().currency == v2.get<Issue>().currency;
if (v1.holds<MPTIssue>() && v2.holds<MPTIssue>())
return v1.get<MPTIssue>() == v2.get<MPTIssue>();
return false;
}
STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name)
{
std::uint64_t value = sit.get64();
// native or MPT
if ((value & cIssuedCurrency) == 0)
{
if ((value & cMPToken) != 0)
{
// is MPT
mOffset = 0;
mIsNegative = (value & cPositive) == 0;
mValue = (value << 8) | sit.get8();
mAsset = sit.get192();
return;
}
// else is XRP
mAsset = xrpIssue();
// positive
if ((value & cPositive) != 0)
{
mValue = value & cValueMask;
mOffset = 0;
mIsNegative = false;
return;
}
// negative
if (value == 0)
Throw<std::runtime_error>("negative zero is not canonical");
mValue = value & cValueMask;
mOffset = 0;
mIsNegative = true;
return;
}
Issue issue;
issue.currency = sit.get160();
if (isXRP(issue.currency))
Throw<std::runtime_error>("invalid native currency");
issue.account = sit.get160();
if (isXRP(issue.account))
Throw<std::runtime_error>("invalid native account");
// 10 bits for the offset, sign and "not native" flag
int offset = static_cast<int>(value >> (64 - 10));
value &= ~(1023ull << (64 - 10));
if (value)
{
bool isNegative = (offset & 256) == 0;
offset = (offset & 255) - 97; // center the range
if (value < cMinValue || value > cMaxValue || offset < cMinOffset ||
offset > cMaxOffset)
{
Throw<std::runtime_error>("invalid currency value");
}
mAsset = issue;
mValue = value;
mOffset = offset;
mIsNegative = isNegative;
canonicalize();
return;
}
if (offset != 512)
Throw<std::runtime_error>("invalid currency value");
mAsset = issue;
mValue = 0;
mOffset = 0;
mIsNegative = false;
canonicalize();
}
STAmount::STAmount(SField const& name, std::int64_t mantissa)
: STBase(name), mAsset(xrpIssue()), mOffset(0)
{
set(mantissa);
}
STAmount::STAmount(SField const& name, std::uint64_t mantissa, bool negative)
: STBase(name)
, mAsset(xrpIssue())
, mValue(mantissa)
, mOffset(0)
, mIsNegative(negative)
{
XRPL_ASSERT(
mValue <= std::numeric_limits<std::int64_t>::max(),
"ripple::STAmount::STAmount(SField, std::uint64_t, bool) : maximum "
"mantissa input");
}
STAmount::STAmount(SField const& name, STAmount const& from)
: STBase(name)
, mAsset(from.mAsset)
, mValue(from.mValue)
, mOffset(from.mOffset)
, mIsNegative(from.mIsNegative)
{
XRPL_ASSERT(
mValue <= std::numeric_limits<std::int64_t>::max(),
"ripple::STAmount::STAmount(SField, STAmount) : maximum input");
canonicalize();
}
//------------------------------------------------------------------------------
STAmount::STAmount(std::uint64_t mantissa, bool negative)
: mAsset(xrpIssue())
, mValue(mantissa)
, mOffset(0)
, mIsNegative(mantissa != 0 && negative)
{
XRPL_ASSERT(
mValue <= std::numeric_limits<std::int64_t>::max(),
"ripple::STAmount::STAmount(std::uint64_t, bool) : maximum mantissa "
"input");
}
STAmount::STAmount(XRPAmount const& amount)
: mAsset(xrpIssue()), mOffset(0), mIsNegative(amount < beast::zero)
{
if (mIsNegative)
mValue = unsafe_cast<std::uint64_t>(-amount.drops());
else
mValue = unsafe_cast<std::uint64_t>(amount.drops());
canonicalize();
}
std::unique_ptr<STAmount>
STAmount::construct(SerialIter& sit, SField const& name)
{
return std::make_unique<STAmount>(sit, name);
}
STBase*
STAmount::copy(std::size_t n, void* buf) const
{
return emplace(n, buf, *this);
}
STBase*
STAmount::move(std::size_t n, void* buf)
{
return emplace(n, buf, std::move(*this));
}
//------------------------------------------------------------------------------
//
// Conversion
//
//------------------------------------------------------------------------------
XRPAmount
STAmount::xrp() const
{
if (!native())
Throw<std::logic_error>(
"Cannot return non-native STAmount as XRPAmount");
auto drops = static_cast<XRPAmount::value_type>(mValue);
XRPL_ASSERT(mOffset == 0, "ripple::STAmount::xrp : amount is canonical");
if (mIsNegative)
drops = -drops;
return XRPAmount{drops};
}
IOUAmount
STAmount::iou() const
{
if (native() || !holds<Issue>())
Throw<std::logic_error>("Cannot return non-IOU STAmount as IOUAmount");
auto mantissa = static_cast<std::int64_t>(mValue);
auto exponent = mOffset;
if (mIsNegative)
mantissa = -mantissa;
return {mantissa, exponent};
}
MPTAmount
STAmount::mpt() const
{
if (!holds<MPTIssue>())
Throw<std::logic_error>("Cannot return STAmount as MPTAmount");
auto value = static_cast<MPTAmount::value_type>(mValue);
XRPL_ASSERT(mOffset == 0, "ripple::STAmount::mpt : amount is canonical");
if (mIsNegative)
value = -value;
return MPTAmount{value};
}
STAmount&
STAmount::operator=(IOUAmount const& iou)
{
XRPL_ASSERT(
native() == false,
"ripple::STAmount::operator=(IOUAmount) : is not XRP");
mOffset = iou.exponent();
mIsNegative = iou < beast::zero;
if (mIsNegative)
mValue = static_cast<std::uint64_t>(-iou.mantissa());
else
mValue = static_cast<std::uint64_t>(iou.mantissa());
return *this;
}
//------------------------------------------------------------------------------
//
// Operators
//
//------------------------------------------------------------------------------
STAmount&
STAmount::operator+=(STAmount const& a)
{
*this = *this + a;
return *this;
}
STAmount&
STAmount::operator-=(STAmount const& a)
{
*this = *this - a;
return *this;
}
STAmount
operator+(STAmount const& v1, STAmount const& v2)
{
if (!areComparable(v1, v2))
Throw<std::runtime_error>("Can't add amounts that are't comparable!");
if (v2 == beast::zero)
return v1;
if (v1 == beast::zero)
{
// Result must be in terms of v1 currency and issuer.
return {
v1.getFName(),
v1.asset(),
v2.mantissa(),
v2.exponent(),
v2.negative()};
}
if (v1.native())
return {v1.getFName(), getSNValue(v1) + getSNValue(v2)};
if (v1.holds<MPTIssue>())
return {v1.mAsset, v1.mpt().value() + v2.mpt().value()};
if (getSTNumberSwitchover())
{
auto x = v1;
x = v1.iou() + v2.iou();
return x;
}
int ov1 = v1.exponent(), ov2 = v2.exponent();
std::int64_t vv1 = static_cast<std::int64_t>(v1.mantissa());
std::int64_t vv2 = static_cast<std::int64_t>(v2.mantissa());
if (v1.negative())
vv1 = -vv1;
if (v2.negative())
vv2 = -vv2;
while (ov1 < ov2)
{
vv1 /= 10;
++ov1;
}
while (ov2 < ov1)
{
vv2 /= 10;
++ov2;
}
// This addition cannot overflow an std::int64_t. It can overflow an
// STAmount and the constructor will throw.
std::int64_t fv = vv1 + vv2;
if ((fv >= -10) && (fv <= 10))
return {v1.getFName(), v1.asset()};
if (fv >= 0)
return STAmount{
v1.getFName(),
v1.asset(),
static_cast<std::uint64_t>(fv),
ov1,
false};
return STAmount{
v1.getFName(), v1.asset(), static_cast<std::uint64_t>(-fv), ov1, true};
}
STAmount
operator-(STAmount const& v1, STAmount const& v2)
{
return v1 + (-v2);
}
//------------------------------------------------------------------------------
std::uint64_t const STAmount::uRateOne = getRate(STAmount(1), STAmount(1));
void
STAmount::setIssue(Asset const& asset)
{
mAsset = asset;
}
// Convert an offer into an index amount so they sort by rate.
// A taker will take the best, lowest, rate first.
// (e.g. a taker will prefer pay 1 get 3 over pay 1 get 2.
// --> offerOut: takerGets: How much the offerer is selling to the taker.
// --> offerIn: takerPays: How much the offerer is receiving from the taker.
// <-- uRate: normalize(offerIn/offerOut)
// A lower rate is better for the person taking the order.
// The taker gets more for less with a lower rate.
// Zero is returned if the offer is worthless.
std::uint64_t
getRate(STAmount const& offerOut, STAmount const& offerIn)
{
if (offerOut == beast::zero)
return 0;
try
{
STAmount r = divide(offerIn, offerOut, noIssue());
if (r == beast::zero) // offer is too good
return 0;
XRPL_ASSERT(
(r.exponent() >= -100) && (r.exponent() <= 155),
"ripple::getRate : exponent inside range");
std::uint64_t ret = r.exponent() + 100;
return (ret << (64 - 8)) | r.mantissa();
}
catch (std::exception const&)
{
}
// overflow -- very bad offer
return 0;
}
/**
* @brief Safely checks if two STAmount values can be added without overflow,
* underflow, or precision loss.
*
* This function determines whether the addition of two STAmount objects is
* safe, depending on their type:
* - For XRP amounts, it checks for integer overflow and underflow.
* - For IOU amounts, it checks for acceptable precision loss.
* - For MPT amounts, it checks for overflow and underflow within 63-bit signed
* integer limits.
* - If either amount is zero, addition is always considered safe.
* - If the amounts are of different currencies or types, addition is not
* allowed.
*
* @param a The first STAmount to add.
* @param b The second STAmount to add.
* @return true if the addition is safe; false otherwise.
*/
bool
canAdd(STAmount const& a, STAmount const& b)
{
// cannot add different currencies
if (!areComparable(a, b))
return false;
// special case: adding anything to zero is always fine
if (a == beast::zero || b == beast::zero)
return true;
// XRP case (overflow & underflow check)
if (isXRP(a) && isXRP(b))
{
XRPAmount A = a.xrp();
XRPAmount B = b.xrp();
if ((B > XRPAmount{0} &&
A > XRPAmount{std::numeric_limits<XRPAmount::value_type>::max()} -
B) ||
(B < XRPAmount{0} &&
A < XRPAmount{std::numeric_limits<XRPAmount::value_type>::min()} -
B))
{
return false;
}
return true;
}
// IOU case (precision check)
if (a.holds<Issue>() && b.holds<Issue>())
{
static STAmount const one{IOUAmount{1, 0}, noIssue()};
static STAmount const maxLoss{IOUAmount{1, -4}, noIssue()};
STAmount lhs = divide((a - b) + b, a, noIssue()) - one;
STAmount rhs = divide((b - a) + a, b, noIssue()) - one;
return ((rhs.negative() ? -rhs : rhs) +
(lhs.negative() ? -lhs : lhs)) <= maxLoss;
}
// MPT (overflow & underflow check)
if (a.holds<MPTIssue>() && b.holds<MPTIssue>())
{
MPTAmount A = a.mpt();
MPTAmount B = b.mpt();
if ((B > MPTAmount{0} &&
A > MPTAmount{std::numeric_limits<MPTAmount::value_type>::max()} -
B) ||
(B < MPTAmount{0} &&
A < MPTAmount{std::numeric_limits<MPTAmount::value_type>::min()} -
B))
{
return false;
}
return true;
}
// LCOV_EXCL_START
UNREACHABLE("STAmount::canAdd : unexpected STAmount type");
return false;
// LCOV_EXCL_STOP
}
/**
* @brief Determines if it is safe to subtract one STAmount from another.
*
* This function checks whether subtracting amount `b` from amount `a` is valid,
* considering currency compatibility and underflow conditions for specific
* types.
*
* - Subtracting zero is always allowed.
* - Subtraction is only allowed between comparable currencies.
* - For XRP amounts, ensures no underflow or overflow occurs.
* - For IOU amounts, subtraction is always allowed (no underflow).
* - For MPT amounts, ensures no underflow or overflow occurs.
*
* @param a The minuend (amount to subtract from).
* @param b The subtrahend (amount to subtract).
* @return true if subtraction is allowed, false otherwise.
*/
bool
canSubtract(STAmount const& a, STAmount const& b)
{
// Cannot subtract different currencies
if (!areComparable(a, b))
return false;
// Special case: subtracting zero is always fine
if (b == beast::zero)
return true;
// XRP case (underflow & overflow check)
if (isXRP(a) && isXRP(b))
{
XRPAmount A = a.xrp();
XRPAmount B = b.xrp();
// Check for underflow
if (B > XRPAmount{0} && A < B)
return false;
// Check for overflow
if (B < XRPAmount{0} &&
A > XRPAmount{std::numeric_limits<XRPAmount::value_type>::max()} +
B)
return false;
return true;
}
// IOU case (no underflow)
if (a.holds<Issue>() && b.holds<Issue>())
{
return true;
}
// MPT case (underflow & overflow check)
if (a.holds<MPTIssue>() && b.holds<MPTIssue>())
{
MPTAmount A = a.mpt();
MPTAmount B = b.mpt();
// Underflow check
if (B > MPTAmount{0} && A < B)
return false;
// Overflow check
if (B < MPTAmount{0} &&
A > MPTAmount{std::numeric_limits<MPTAmount::value_type>::max()} +
B)
return false;
return true;
}
// LCOV_EXCL_START
UNREACHABLE("STAmount::canSubtract : unexpected STAmount type");
return false;
// LCOV_EXCL_STOP
}
void
STAmount::setJson(Json::Value& elem) const
{
elem = Json::objectValue;
if (!native())
{
// It is an error for currency or issuer not to be specified for valid
// json.
elem[jss::value] = getText();
mAsset.setJson(elem);
}
else
{
elem = getText();
}
}
//------------------------------------------------------------------------------
//
// STBase
//
//------------------------------------------------------------------------------
SerializedTypeID
STAmount::getSType() const
{
return STI_AMOUNT;
}
std::string
STAmount::getFullText() const
{
std::string ret;
ret.reserve(64);
ret = getText() + "/" + mAsset.getText();
return ret;
}
std::string
STAmount::getText() const
{
// keep full internal accuracy, but make more human friendly if posible
if (*this == beast::zero)
return "0";
std::string const raw_value(std::to_string(mValue));
std::string ret;
if (mIsNegative)
ret.append(1, '-');
bool const scientific(
(mOffset != 0) && ((mOffset < -25) || (mOffset > -5)));
if (native() || mAsset.holds<MPTIssue>() || scientific)
{
ret.append(raw_value);
if (scientific)
{
ret.append(1, 'e');
ret.append(std::to_string(mOffset));
}
return ret;
}
XRPL_ASSERT(mOffset + 43 > 0, "ripple::STAmount::getText : minimum offset");
size_t const pad_prefix = 27;
size_t const pad_suffix = 23;
std::string val;
val.reserve(raw_value.length() + pad_prefix + pad_suffix);
val.append(pad_prefix, '0');
val.append(raw_value);
val.append(pad_suffix, '0');
size_t const offset(mOffset + 43);
auto pre_from(val.begin());
auto const pre_to(val.begin() + offset);
auto const post_from(val.begin() + offset);
auto post_to(val.end());
// Crop leading zeroes. Take advantage of the fact that there's always a
// fixed amount of leading zeroes and skip them.
if (std::distance(pre_from, pre_to) > pad_prefix)
pre_from += pad_prefix;
XRPL_ASSERT(
post_to >= post_from,
"ripple::STAmount::getText : first distance check");
pre_from = std::find_if(pre_from, pre_to, [](char c) { return c != '0'; });
// Crop trailing zeroes. Take advantage of the fact that there's always a
// fixed amount of trailing zeroes and skip them.
if (std::distance(post_from, post_to) > pad_suffix)
post_to -= pad_suffix;
XRPL_ASSERT(
post_to >= post_from,
"ripple::STAmount::getText : second distance check");
post_to = std::find_if(
std::make_reverse_iterator(post_to),
std::make_reverse_iterator(post_from),
[](char c) { return c != '0'; })
.base();
// Assemble the output:
if (pre_from == pre_to)
ret.append(1, '0');
else
ret.append(pre_from, pre_to);
if (post_to != post_from)
{
ret.append(1, '.');
ret.append(post_from, post_to);
}
return ret;
}
Json::Value
STAmount::getJson(JsonOptions) const
{
Json::Value elem;
setJson(elem);
return elem;
}
void
STAmount::add(Serializer& s) const
{
if (native())
{
XRPL_ASSERT(mOffset == 0, "ripple::STAmount::add : zero offset");
if (!mIsNegative)
s.add64(mValue | cPositive);
else
s.add64(mValue);
}
else if (mAsset.holds<MPTIssue>())
{
auto u8 = static_cast<unsigned char>(cMPToken >> 56);
if (!mIsNegative)
u8 |= static_cast<unsigned char>(cPositive >> 56);
s.add8(u8);
s.add64(mValue);
s.addBitString(mAsset.get<MPTIssue>().getMptID());
}
else
{
if (*this == beast::zero)
s.add64(cIssuedCurrency);
else if (mIsNegative) // 512 = not native
s.add64(
mValue |
(static_cast<std::uint64_t>(mOffset + 512 + 97) << (64 - 10)));
else // 256 = positive
s.add64(
mValue |
(static_cast<std::uint64_t>(mOffset + 512 + 256 + 97)
<< (64 - 10)));
s.addBitString(mAsset.get<Issue>().currency);
s.addBitString(mAsset.get<Issue>().account);
}
}
bool
STAmount::isEquivalent(STBase const& t) const
{
STAmount const* v = dynamic_cast<STAmount const*>(&t);
return v && (*v == *this);
}
bool
STAmount::isDefault() const
{
return (mValue == 0) && native();
}
//------------------------------------------------------------------------------
// amount = mValue * [10 ^ mOffset]
// Representation range is 10^80 - 10^(-80).
//
// On the wire:
// - high bit is 0 for XRP, 1 for issued currency
// - next bit is 1 for positive, 0 for negative (except 0 issued currency, which
// is a special case of 0x8000000000000000
// - for issued currencies, the next 8 bits are (mOffset+97).
// The +97 is so that this value is always positive.
// - The remaining bits are significant digits (mantissa)
// That's 54 bits for issued currency and 62 bits for native
// (but XRP only needs 57 bits for the max value of 10^17 drops)
//
// mValue is zero if the amount is zero, otherwise it's within the range
// 10^15 to (10^16 - 1) inclusive.
// mOffset is in the range -96 to +80.
void
STAmount::canonicalize()
{
if (native() || mAsset.holds<MPTIssue>())
{
// native and MPT currency amounts should always have an offset of zero
// log(2^64,10) ~ 19.2
if (mValue == 0 || mOffset <= -20)
{
mValue = 0;
mOffset = 0;
mIsNegative = false;
return;
}
if (getSTAmountCanonicalizeSwitchover())
{
// log(cMaxNativeN, 10) == 17
if (native() && mOffset > 17)
Throw<std::runtime_error>(
"Native currency amount out of range");
// log(maxMPTokenAmount, 10) ~ 18.96
if (mAsset.holds<MPTIssue>() && mOffset > 18)
Throw<std::runtime_error>("MPT amount out of range");
}
if (getSTNumberSwitchover() && getSTAmountCanonicalizeSwitchover())
{
Number num(
mIsNegative ? -mValue : mValue, mOffset, Number::unchecked{});
auto set = [&](auto const& val) {
mIsNegative = val.value() < 0;
mValue = mIsNegative ? -val.value() : val.value();
};
if (native())
set(XRPAmount{num});
else
set(MPTAmount{num});
mOffset = 0;
}
else
{
while (mOffset < 0)
{
mValue /= 10;
++mOffset;
}
while (mOffset > 0)
{
if (getSTAmountCanonicalizeSwitchover())
{
// N.B. do not move the overflow check to after the
// multiplication
if (native() && mValue > cMaxNativeN)
Throw<std::runtime_error>(
"Native currency amount out of range");
else if (!native() && mValue > maxMPTokenAmount)
Throw<std::runtime_error>("MPT amount out of range");
}
mValue *= 10;
--mOffset;
}
}
if (native() && mValue > cMaxNativeN)
Throw<std::runtime_error>("Native currency amount out of range");
else if (!native() && mValue > maxMPTokenAmount)
Throw<std::runtime_error>("MPT amount out of range");
return;
}
if (getSTNumberSwitchover())
{
*this = iou();
return;
}
if (mValue == 0)
{
mOffset = -100;
mIsNegative = false;
return;
}
while ((mValue < cMinValue) && (mOffset > cMinOffset))
{
mValue *= 10;
--mOffset;
}
while (mValue > cMaxValue)
{
if (mOffset >= cMaxOffset)
Throw<std::runtime_error>("value overflow");
mValue /= 10;
++mOffset;
}
if ((mOffset < cMinOffset) || (mValue < cMinValue))
{
mValue = 0;
mIsNegative = false;
mOffset = -100;
return;
}
if (mOffset > cMaxOffset)
Throw<std::runtime_error>("value overflow");
XRPL_ASSERT(
(mValue == 0) || ((mValue >= cMinValue) && (mValue <= cMaxValue)),
"ripple::STAmount::canonicalize : value inside range");
XRPL_ASSERT(
(mValue == 0) || ((mOffset >= cMinOffset) && (mOffset <= cMaxOffset)),
"ripple::STAmount::canonicalize : offset inside range");
XRPL_ASSERT(
(mValue != 0) || (mOffset != -100),
"ripple::STAmount::canonicalize : value or offset set");
}
void
STAmount::set(std::int64_t v)
{
if (v < 0)
{
mIsNegative = true;