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
| using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System;
namespace MongoTest
{
class Program
{
static void Main(string[] args)
{
var model = new DoubleSpendDemo();
Console.WriteLine("Transaction Approach:");
model.RunAsync(model.DecreaseBalanceAsync).Wait();
Console.WriteLine("----------------------------------------------");
Console.WriteLine("Versioning Approach:");
model.RunAsync(model.DecreaseBalanceWithVersionAsync).Wait();
Console.WriteLine("Done");
}
}
public class AccountEntry
{
public string Uuid { get; set; }
public decimal Balance { get; set; }
public int Version { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
}
public class TransResult
{
public decimal NewBalance { get; set; } = 0;
public TransCode Code { get; set; }
}
public enum TransCode
{
Success = 0,
ConcurrentUpdateFailure = 1,
InsufficientBalance = 2
}
public class DoubleSpendDemo
{
private readonly IMongoClient _mongoClient;
private readonly IMongoCollection<AccountEntry> _accountCollection;
private const string DatabaseName = "Transaction";
private const string AccountCollectionName = "Account";
public const string ConnectionString = "";
public DoubleSpendDemo()
{
_mongoClient = new MongoClient(ConnectionString);
var database = _mongoClient.GetDatabase(DatabaseName);
var ignoreExtraElementsConvention = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", ignoreExtraElementsConvention, type => true);
_accountCollection = database.GetCollection<AccountEntry>(AccountCollectionName);
}
public static string GenerateAccountUuid() => $"Acc_{Guid.NewGuid().ToString("N").ToUpper()}";
public async Task<AccountEntry> CreateAccountAsync(string uuid, decimal initBalance)
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
{
var newAccount = new AccountEntry
{
Uuid = uuid,
Balance = initBalance,
CreateTime = DateTime.UtcNow,
UpdateTime = DateTime.UtcNow
};
await _accountCollection.InsertOneAsync(newAccount, cancellationToken: cts.Token);
return newAccount;
}
}
public async Task<TransResult> DecreaseBalanceAsync(string accountId, decimal amount)
{
if (amount <= 0)
{
throw new ArgumentException("Amount should > 0");
}
using (var session = await _mongoClient.StartSessionAsync())
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
{
return await session.WithTransactionAsync(
async (s, ct) =>
{
var accountEntry = await _accountCollection.Find(s, x => x.Uuid == accountId).FirstOrDefaultAsync(ct);
if (accountEntry.Balance < amount)
{
return new TransResult { Code = TransCode.InsufficientBalance };
}
var filter = Builders<AccountEntry>.Filter.And(
Builders<AccountEntry>.Filter.Eq(x => x.Uuid, accountId),
Builders<AccountEntry>.Filter.Gte(x => x.Balance, amount));
var update = Builders<AccountEntry>.Update
.Inc(x => x.Balance, -amount)
.Set(x => x.UpdateTime, DateTime.UtcNow);
var options = new FindOneAndUpdateOptions<AccountEntry> { ReturnDocument = ReturnDocument.After };
var result = await _accountCollection.FindOneAndUpdateAsync(s, filter, update, options, cancellationToken: ct);
return new TransResult { NewBalance = result.Balance };
}, cancellationToken: cts.Token);
}
}
public async Task<TransResult> DecreaseBalanceWithVersionAsync(string accountId, decimal amount)
{
if (amount <= 0)
{
throw new ArgumentException("Amount should > 0");
}
var accountEntry = await _accountCollection.Find(x => x.Uuid == accountId).FirstOrDefaultAsync();
if (accountEntry.Balance < amount)
{
return new TransResult { Code = TransCode.InsufficientBalance };
}
var filter = Builders<AccountEntry>.Filter.And(
Builders<AccountEntry>.Filter.Eq(x => x.Uuid, accountId),
Builders<AccountEntry>.Filter.Eq(x => x.Version, accountEntry.Version) // Match the current version
);
var update = Builders<AccountEntry>.Update
.Inc(x => x.Balance, -amount)
.Inc(x => x.Version, 1) // Increment version
.Set(x => x.UpdateTime, DateTime.UtcNow);
var options = new FindOneAndUpdateOptions<AccountEntry> { ReturnDocument = ReturnDocument.After };
var result = await _accountCollection.FindOneAndUpdateAsync(filter, update, options);
if (result == null)
{
return new TransResult { Code = TransCode.ConcurrentUpdateFailure };
}
return new TransResult { NewBalance = result.Balance };
}
public async Task RunAsync(Func<string, decimal, Task<TransResult>> func)
{
var tasks = new List<Task>();
string accountId = Guid.NewGuid().ToString();
var account = await CreateAccountAsync(accountId, 100m);
for (int i = 0; i < 5; i++)
{
var cur = i;
tasks.Add(Task.Run(async () =>
{
var r = await func(accountId, 60);
Console.WriteLine($"Task {cur}: code: {r.Code.ToString()}");
}));
}
await Task.WhenAll(tasks);
var updatedAccount = await _accountCollection.Find(x => x.Uuid == accountId).FirstOrDefaultAsync();
Console.WriteLine($"Account {accountId} Final Balance: {updatedAccount.Balance}");
}
}
}
|