|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Runtime.InteropServices; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using LiteDB; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using NBitcoin; |
| 11 | +using Newtonsoft.Json; |
| 12 | +using Stratis.Bitcoin.AsyncWork; |
| 13 | +using Stratis.Bitcoin.Configuration; |
| 14 | +using Stratis.Bitcoin.Features.BlockStore.AddressIndexing; |
| 15 | +using Stratis.Bitcoin.Features.SmartContracts.Models; |
| 16 | +using Stratis.Bitcoin.Features.SmartContracts.Wallet; |
| 17 | +using FileMode = LiteDB.FileMode; |
| 18 | + |
| 19 | +namespace Stratis.Features.Unity3dApi |
| 20 | +{ |
| 21 | + public interface INFTTransferIndexer : IDisposable |
| 22 | + { |
| 23 | + /// <summary>Initialized NFT indexer.</summary> |
| 24 | + void Initialize(); |
| 25 | + |
| 26 | + /// <summary>Adds NFT contract to watch list. Only contracts from the watch list are being indexed.</summary> |
| 27 | + void WatchNFTContract(string contractAddress); |
| 28 | + |
| 29 | + /// <summary>Provides a list of all nft contract addresses that are being tracked.</summary> |
| 30 | + List<string> GetWatchedNFTContracts(); |
| 31 | + |
| 32 | + /// <summary>Provides collection of NFT ids that belong to provided user's address for watched contracts.</summary> |
| 33 | + OwnedNFTsModel GetOwnedNFTs(string address); |
| 34 | + |
| 35 | + /// <summary>Returns collection of all users that own nft.</summary> |
| 36 | + NFTContractModel GetAllNFTOwnersByContractAddress(string contractAddress); |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary>This component maps addresses to NFT Ids they own.</summary> |
| 40 | + public class NFTTransferIndexer : INFTTransferIndexer |
| 41 | + { |
| 42 | + public ChainedHeader IndexerTip { get; private set; } |
| 43 | + |
| 44 | + private const string DatabaseFilename = "NFTTransferIndexer.litedb"; |
| 45 | + private const string DbOwnedNFTsKey = "OwnedNfts"; |
| 46 | + private const int SyncBufferBlocks = 50; |
| 47 | + |
| 48 | + private readonly DataFolder dataFolder; |
| 49 | + private readonly ILogger logger; |
| 50 | + private readonly ChainIndexer chainIndexer; |
| 51 | + private readonly IAsyncProvider asyncProvider; |
| 52 | + private readonly ISmartContractTransactionService smartContractTransactionService; |
| 53 | + |
| 54 | + private LiteDatabase db; |
| 55 | + private LiteCollection<NFTContractModel> NFTContractCollection; |
| 56 | + private CancellationTokenSource cancellation; |
| 57 | + private Task indexingTask; |
| 58 | + |
| 59 | + public NFTTransferIndexer(DataFolder dataFolder, ILoggerFactory loggerFactory, IAsyncProvider asyncProvider, ChainIndexer chainIndexer, ISmartContractTransactionService smartContractTransactionService) |
| 60 | + { |
| 61 | + this.dataFolder = dataFolder; |
| 62 | + this.cancellation = new CancellationTokenSource(); |
| 63 | + this.asyncProvider = asyncProvider; |
| 64 | + this.chainIndexer = chainIndexer; |
| 65 | + this.smartContractTransactionService = smartContractTransactionService; |
| 66 | + |
| 67 | + this.logger = loggerFactory.CreateLogger(this.GetType().FullName); |
| 68 | + } |
| 69 | + |
| 70 | + /// <inheritdoc /> |
| 71 | + public void Initialize() |
| 72 | + { |
| 73 | + if (this.db != null) |
| 74 | + throw new Exception("NFTTransferIndexer already initialized!"); |
| 75 | + |
| 76 | + string dbPath = Path.Combine(this.dataFolder.RootPath, DatabaseFilename); |
| 77 | + |
| 78 | + FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared; |
| 79 | + this.db = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode }); |
| 80 | + this.NFTContractCollection = this.db.GetCollection<NFTContractModel>(DbOwnedNFTsKey); |
| 81 | + |
| 82 | + this.indexingTask = Task.Run(async () => await this.IndexNFTsContinuouslyAsync().ConfigureAwait(false)); |
| 83 | + this.asyncProvider.RegisterTask($"{nameof(AddressIndexer)}.{nameof(this.indexingTask)}", this.indexingTask); |
| 84 | + } |
| 85 | + |
| 86 | + /// <inheritdoc /> |
| 87 | + public void WatchNFTContract(string contractAddress) |
| 88 | + { |
| 89 | + if (!this.NFTContractCollection.Exists(x => x.ContractAddress == contractAddress)) |
| 90 | + { |
| 91 | + NFTContractModel model = new NFTContractModel() |
| 92 | + { |
| 93 | + ContractAddress = contractAddress, |
| 94 | + LastUpdatedBlock = 0, |
| 95 | + OwnedIDsByAddress = new Dictionary<string, List<long>>() |
| 96 | + }; |
| 97 | + |
| 98 | + this.NFTContractCollection.Upsert(model); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + /// <inheritdoc /> |
| 103 | + public List<string> GetWatchedNFTContracts() |
| 104 | + { |
| 105 | + return this.NFTContractCollection.FindAll().Select(x => x.ContractAddress).ToList(); |
| 106 | + } |
| 107 | + |
| 108 | + /// <inheritdoc /> |
| 109 | + public OwnedNFTsModel GetOwnedNFTs(string address) |
| 110 | + { |
| 111 | + List<NFTContractModel> NFTContractModels = this.NFTContractCollection.FindAll().Where(x => x.OwnedIDsByAddress.ContainsKey(address)).ToList(); |
| 112 | + |
| 113 | + OwnedNFTsModel output = new OwnedNFTsModel() { OwnedIDsByContractAddress = new Dictionary<string, List<long>>() }; |
| 114 | + |
| 115 | + foreach (NFTContractModel contractModel in NFTContractModels) |
| 116 | + { |
| 117 | + List<long> ids = contractModel.OwnedIDsByAddress[address]; |
| 118 | + output.OwnedIDsByContractAddress.Add(contractModel.ContractAddress, ids); |
| 119 | + } |
| 120 | + |
| 121 | + return output; |
| 122 | + } |
| 123 | + |
| 124 | + public NFTContractModel GetAllNFTOwnersByContractAddress(string contractAddress) |
| 125 | + { |
| 126 | + NFTContractModel currentContract = this.NFTContractCollection.FindOne(x => x.ContractAddress == contractAddress); |
| 127 | + return currentContract; |
| 128 | + } |
| 129 | + |
| 130 | + private async Task IndexNFTsContinuouslyAsync() |
| 131 | + { |
| 132 | + await Task.Delay(1); |
| 133 | + |
| 134 | + try |
| 135 | + { |
| 136 | + while (!this.cancellation.Token.IsCancellationRequested) |
| 137 | + { |
| 138 | + List<string> contracts = this.NFTContractCollection.FindAll().Select(x => x.ContractAddress).ToList(); |
| 139 | + |
| 140 | + foreach (string contractAddr in contracts) |
| 141 | + { |
| 142 | + if (this.cancellation.Token.IsCancellationRequested) |
| 143 | + break; |
| 144 | + |
| 145 | + NFTContractModel currentContract = this.NFTContractCollection.FindOne(x => x.ContractAddress == contractAddr); |
| 146 | + |
| 147 | + ChainedHeader chainTip = this.chainIndexer.Tip; |
| 148 | + |
| 149 | + List<ReceiptResponse> receipts = this.smartContractTransactionService.ReceiptSearch( |
| 150 | + contractAddr, "TransferLog", null, currentContract.LastUpdatedBlock, null); |
| 151 | + |
| 152 | + if (receipts == null) |
| 153 | + continue; |
| 154 | + |
| 155 | + int lastReceiptHeight = 0; |
| 156 | + if (receipts.Any()) |
| 157 | + lastReceiptHeight = (int)receipts.Last().BlockNumber.Value; |
| 158 | + |
| 159 | + currentContract.LastUpdatedBlock = new List<int>() { chainTip.Height, lastReceiptHeight }.Max(); |
| 160 | + |
| 161 | + List<TransferLog> transferLogs = new List<TransferLog>(receipts.Count); |
| 162 | + |
| 163 | + foreach (ReceiptResponse receiptRes in receipts) |
| 164 | + { |
| 165 | + string jsonLog = Newtonsoft.Json.JsonConvert.SerializeObject(receiptRes.Logs.First().Log); |
| 166 | + |
| 167 | + TransferLog infoObj = JsonConvert.DeserializeObject<TransferLog>(jsonLog); |
| 168 | + transferLogs.Add(infoObj); |
| 169 | + } |
| 170 | + |
| 171 | + foreach (TransferLog transferInfo in transferLogs) |
| 172 | + { |
| 173 | + if (currentContract.OwnedIDsByAddress.ContainsKey(transferInfo.From)) |
| 174 | + { |
| 175 | + currentContract.OwnedIDsByAddress[transferInfo.From].Remove(transferInfo.TokenId); |
| 176 | + |
| 177 | + if (currentContract.OwnedIDsByAddress[transferInfo.From].Count == 0) |
| 178 | + currentContract.OwnedIDsByAddress.Remove(transferInfo.From); |
| 179 | + } |
| 180 | + |
| 181 | + if (!currentContract.OwnedIDsByAddress.ContainsKey(transferInfo.To)) |
| 182 | + currentContract.OwnedIDsByAddress.Add(transferInfo.To, new List<long>()); |
| 183 | + |
| 184 | + currentContract.OwnedIDsByAddress[transferInfo.To].Add(transferInfo.TokenId); |
| 185 | + } |
| 186 | + |
| 187 | + this.NFTContractCollection.Upsert(currentContract); |
| 188 | + } |
| 189 | + |
| 190 | + try |
| 191 | + { |
| 192 | + await Task.Delay(TimeSpan.FromSeconds(6), this.cancellation.Token); |
| 193 | + } |
| 194 | + catch (TaskCanceledException) |
| 195 | + { |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + catch (Exception e) |
| 200 | + { |
| 201 | + this.logger.LogError(e.ToString()); |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + public void Dispose() |
| 206 | + { |
| 207 | + this.cancellation.Cancel(); |
| 208 | + this.indexingTask?.GetAwaiter().GetResult(); |
| 209 | + this.db?.Dispose(); |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + public class NFTContractModel |
| 214 | + { |
| 215 | + public int Id { get; set; } |
| 216 | + |
| 217 | + public string ContractAddress { get; set; } |
| 218 | + |
| 219 | + // Key is nft owner address, value is list of NFT IDs |
| 220 | + public Dictionary<string, List<long>> OwnedIDsByAddress { get; set; } |
| 221 | + |
| 222 | + public int LastUpdatedBlock { get; set; } |
| 223 | + } |
| 224 | + |
| 225 | + public class OwnedNFTsModel |
| 226 | + { |
| 227 | + public Dictionary<string, List<long>> OwnedIDsByContractAddress { get; set; } |
| 228 | + } |
| 229 | + |
| 230 | + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")] |
| 231 | + public partial class TransferLog |
| 232 | + { |
| 233 | + [JsonProperty("from", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] |
| 234 | + public string From { get; set; } |
| 235 | + |
| 236 | + [JsonProperty("to", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] |
| 237 | + public string To { get; set; } |
| 238 | + |
| 239 | + [JsonProperty("tokenId", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)] |
| 240 | + public long TokenId { get; set; } |
| 241 | + } |
| 242 | +} |
0 commit comments