/// <summary>
 /// Initializes a new instance of the MigrationConfirmStatusRequest
 /// class with required arguments.
 /// </summary>
 public MigrationConfirmStatusRequest(List<string> dataContainerNameList, MigrationOperation operation)
     : this()
 {
     if (dataContainerNameList == null)
     {
         throw new ArgumentNullException("dataContainerNameList");
     }
     this.DataContainerNameList = dataContainerNameList;
     this.Operation = operation;
 }
 /// <summary>
 /// 添加索引的相关定义。
 /// </summary>
 /// <param name="operation">操作实例。</param>
 /// <param name="builder"><see cref="MigrationCommandListBuilder"/>实例。</param>
 /// <param name="isPrimaryKey">是否为主键。</param>
 protected virtual void IndexTraits(
     [NotNull] MigrationOperation operation,
     [NotNull] MigrationCommandListBuilder builder,
     bool isPrimaryKey = false)
 {
 }
 protected IEnumerable <MigrationStatement> Generate(MigrationOperation operation)
 {
     throw new NotSupportedException(string.Format("Unknown operation '{0}'.", operation.GetType().FullName));
 }
Esempio n. 4
0
 public virtual void IndexTraits(
     [NotNull] MigrationOperation operation,
     [CanBeNull] IModel model,
     [NotNull] SqlBatchBuilder builder)
 {
 }
Esempio n. 5
0
        async Task <List <Account> > BootstrapAccounts(Protocol protocol, JToken parameters)
        {
            var bootstrapAccounts = parameters["bootstrap_accounts"]?
                                    .Select(x => (x[0].Value <string>(), x[1].Value <long>()))
                                    .ToList() ?? new(0);

            var bootstrapContracts = parameters["bootstrap_contracts"]?
                                     .Select(x =>
                                             (
                                                 x["amount"].Value <long>(),
                                                 x["delegate"]?.Value <string>() ?? null,
                                                 x["script"]["code"].ToString(),
                                                 x["script"]["storage"].ToString())
                                             )
                                     .ToList() ?? new(0);

            var accounts = new List <Account>(bootstrapAccounts.Count + bootstrapContracts.Count);

            #region allocate null-address
            var nullAddress = (User)await Cache.Accounts.GetAsync(NullAddress.Address);

            if (nullAddress.Id != NullAddress.Id)
            {
                throw new Exception("Failed to allocate null-address");
            }
            #endregion

            #region bootstrap delegates
            foreach (var(pubKey, balance) in bootstrapAccounts.Where(x => x.Item1[0] != 't'))
            {
                var baker = new Data.Models.Delegate
                {
                    Id                = Cache.AppState.NextAccountId(),
                    Address           = PubKey.FromBase58(pubKey).Address,
                    Balance           = balance,
                    StakingBalance    = balance,
                    Counter           = 0,
                    PublicKey         = pubKey,
                    FirstLevel        = 1,
                    LastLevel         = 1,
                    ActivationLevel   = 1,
                    DeactivationLevel = GracePeriod.Init(2, protocol),
                    Staked            = true,
                    Revealed          = true,
                    Type              = AccountType.Delegate
                };
                Cache.Accounts.Add(baker);
                accounts.Add(baker);
            }
            #endregion

            #region bootstrap users
            foreach (var(pkh, balance) in bootstrapAccounts.Where(x => x.Item1[0] == 't'))
            {
                var user = new User
                {
                    Id         = Cache.AppState.NextAccountId(),
                    Address    = pkh,
                    Balance    = balance,
                    Counter    = 0,
                    FirstLevel = 1,
                    LastLevel  = 1,
                    Type       = AccountType.User
                };
                Cache.Accounts.Add(user);
                accounts.Add(user);
            }
            #endregion

            #region bootstrap contracts
            var index = 0;
            foreach (var(balance, delegatePkh, codeStr, storageStr) in bootstrapContracts)
            {
                #region contract
                var delegat = Cache.Accounts.GetDelegate(delegatePkh);
                var manager = nullAddress;

                var contract = new Contract
                {
                    Id              = Cache.AppState.NextAccountId(),
                    Address         = OriginationNonce.GetContractAddress(index++),
                    Balance         = balance,
                    Counter         = 0,
                    FirstLevel      = 1,
                    LastLevel       = 1,
                    Spendable       = false,
                    DelegationLevel = delegat == null ? null : 1,
                    Delegate        = delegat,
                    Manager         = manager,
                    Staked          = delegat != null,
                    Type            = AccountType.Contract,
                    Kind            = ContractKind.SmartContract,
                };

                manager.ContractsCount++;
                if (delegat != null)
                {
                    delegat.DelegatorsCount++;
                    delegat.StakingBalance += contract.Balance;
                }

                Cache.Accounts.Add(contract);
                accounts.Add(contract);
                #endregion

                #region script
                var code           = Micheline.FromJson(codeStr) as MichelineArray;
                var micheParameter = code.First(x => x is MichelinePrim p && p.Prim == PrimType.parameter);
                var micheStorage   = code.First(x => x is MichelinePrim p && p.Prim == PrimType.storage);
                var micheCode      = code.First(x => x is MichelinePrim p && p.Prim == PrimType.code);
                var micheViews     = code.Where(x => x is MichelinePrim p && p.Prim == PrimType.view);
                var script         = new Script
                {
                    Id              = Cache.AppState.NextScriptId(),
                    Level           = 1,
                    ContractId      = contract.Id,
                    ParameterSchema = micheParameter.ToBytes(),
                    StorageSchema   = micheStorage.ToBytes(),
                    CodeSchema      = micheCode.ToBytes(),
                    Views           = micheViews.Any()
                        ? micheViews.Select(x => x.ToBytes()).ToArray()
                        : null,
                    Current = true
                };

                var viewsBytes = script.Views?
                                 .OrderBy(x => x, new BytesComparer())
                                 .SelectMany(x => x)
                                 .ToArray()
                                 ?? Array.Empty <byte>();
                var typeSchema = script.ParameterSchema.Concat(script.StorageSchema).Concat(viewsBytes);
                var fullSchema = typeSchema.Concat(script.CodeSchema);
                contract.TypeHash = script.TypeHash = Script.GetHash(typeSchema);
                contract.CodeHash = script.CodeHash = Script.GetHash(fullSchema);

                if (script.Schema.IsFA1())
                {
                    if (script.Schema.IsFA12())
                    {
                        contract.Tags |= ContractTags.FA12;
                    }

                    contract.Tags |= ContractTags.FA1;
                    contract.Kind  = ContractKind.Asset;
                }
                if (script.Schema.IsFA2())
                {
                    contract.Tags |= ContractTags.FA2;
                    contract.Kind  = ContractKind.Asset;
                }

                Db.Scripts.Add(script);
                Cache.Schemas.Add(contract, script.Schema);
                #endregion

                #region storage
                var storageValue = Micheline.FromJson(storageStr);
                var storage      = new Storage
                {
                    Id         = Cache.AppState.NextStorageId(),
                    Level      = 1,
                    ContractId = contract.Id,
                    RawValue   = script.Schema.OptimizeStorage(storageValue, false).ToBytes(),
                    JsonValue  = script.Schema.HumanizeStorage(storageValue),
                    Current    = true
                };

                Db.Storages.Add(storage);
                Cache.Storages.Add(contract, storage);
                #endregion
            }
            #endregion

            Db.Accounts.AddRange(accounts);

            #region migration ops
            var block = Cache.Blocks.Current();

            block.Operations |= Operations.Migrations;
            if (accounts.Any(x => x.Type == AccountType.Contract))
            {
                block.Events |= BlockEvents.SmartContracts;
            }

            foreach (var account in accounts)
            {
                var migration = new MigrationOperation
                {
                    Id            = Cache.AppState.NextOperationId(),
                    Block         = block,
                    Level         = block.Level,
                    Timestamp     = block.Timestamp,
                    Account       = account,
                    Kind          = MigrationKind.Bootstrap,
                    BalanceChange = account.Balance,
                };

                if (account is Contract contract)
                {
                    var script = Db.ChangeTracker.Entries()
                                 .First(x => x.Entity is Script s && s.ContractId == contract.Id).Entity as Script;
                    var storage = await Cache.Storages.GetAsync(contract);

                    script.MigrationId  = migration.Id;
                    storage.MigrationId = migration.Id;

                    migration.Script  = script;
                    migration.Storage = storage;
                }

                Db.MigrationOps.Add(migration);
                account.MigrationsCount++;
            }

            var state = Cache.AppState.Get();
            state.MigrationOpsCount += accounts.Count;
            #endregion

            #region statistics
            var stats = await Cache.Statistics.GetAsync(1);

            stats.TotalBootstrapped = accounts.Sum(x => x.Balance);
            stats.TotalVested       = accounts.Where(x => x.Type == AccountType.Contract).Sum(x => x.Balance);
            #endregion

            return(accounts);
        }
 protected override void Generate(MigrationOperation migrationOperation)
 {
     this.Generate((dynamic)migrationOperation);
     base.Generate(migrationOperation);
 }
Esempio n. 7
0
 protected override void Generate(MigrationOperation operation, IndentedStringBuilder builder)
 {
     //base.Generate(operation, builder);
 }
 protected override void VisitDefault(MigrationOperation operation, IndentedStringBuilder builder)
 {
     builder.Append(operation.GetType().Name).Append("Sql");
 }
Esempio n. 9
0
        async Task OriginateContract(Block block, string address)
        {
            var rawContract = await Proto.Rpc.GetContractAsync(block.Level, address);

            #region contract
            var contract = new Contract
            {
                Id              = Cache.AppState.NextAccountId(),
                FirstBlock      = block,
                Address         = address,
                Balance         = rawContract.RequiredInt64("balance"),
                Creator         = await Cache.Accounts.GetAsync(NullAddress.Address),
                Type            = AccountType.Contract,
                Kind            = ContractKind.SmartContract,
                MigrationsCount = 1,
            };

            Db.TryAttach(contract.Creator);
            contract.Creator.ContractsCount++;

            Db.Accounts.Add(contract);
            #endregion

            #region script
            var code           = Micheline.FromJson(rawContract.Required("script").Required("code")) as MichelineArray;
            var micheParameter = code.First(x => x is MichelinePrim p && p.Prim == PrimType.parameter);
            var micheStorage   = code.First(x => x is MichelinePrim p && p.Prim == PrimType.storage);
            var micheCode      = code.First(x => x is MichelinePrim p && p.Prim == PrimType.code);
            var micheViews     = code.Where(x => x is MichelinePrim p && p.Prim == PrimType.view);
            var script         = new Script
            {
                Id              = Cache.AppState.NextScriptId(),
                Level           = block.Level,
                ContractId      = contract.Id,
                ParameterSchema = micheParameter.ToBytes(),
                StorageSchema   = micheStorage.ToBytes(),
                CodeSchema      = micheCode.ToBytes(),
                Views           = micheViews.Any()
                    ? micheViews.Select(x => x.ToBytes()).ToArray()
                    : null,
                Current = true
            };

            var viewsBytes = script.Views?
                             .OrderBy(x => x, new BytesComparer())
                             .SelectMany(x => x)
                             .ToArray()
                             ?? Array.Empty <byte>();
            var typeSchema = script.ParameterSchema.Concat(script.StorageSchema).Concat(viewsBytes);
            var fullSchema = typeSchema.Concat(script.CodeSchema);
            contract.TypeHash = script.TypeHash = Script.GetHash(typeSchema);
            contract.CodeHash = script.CodeHash = Script.GetHash(fullSchema);

            if (script.Schema.IsFA1())
            {
                if (script.Schema.IsFA12())
                {
                    contract.Tags |= ContractTags.FA12;
                }

                contract.Tags |= ContractTags.FA1;
                contract.Kind  = ContractKind.Asset;
            }
            if (script.Schema.IsFA2())
            {
                contract.Tags |= ContractTags.FA2;
                contract.Kind  = ContractKind.Asset;
            }

            Db.Scripts.Add(script);
            #endregion

            #region storage
            var storageValue = Micheline.FromJson(rawContract.Required("script").Required("storage"));
            var storage      = new Storage
            {
                Id         = Cache.AppState.NextStorageId(),
                Level      = block.Level,
                ContractId = contract.Id,
                RawValue   = script.Schema.OptimizeStorage(storageValue, false).ToBytes(),
                JsonValue  = script.Schema.HumanizeStorage(storageValue),
                Current    = true
            };

            Db.Storages.Add(storage);
            #endregion

            #region migration
            var migration = new MigrationOperation
            {
                Id            = Cache.AppState.NextOperationId(),
                Block         = block,
                Level         = block.Level,
                Timestamp     = block.Timestamp,
                Kind          = MigrationKind.Origination,
                Account       = contract,
                BalanceChange = contract.Balance,
                Script        = script,
                Storage       = storage,
            };

            script.MigrationId  = migration.Id;
            storage.MigrationId = migration.Id;

            block.Events     |= BlockEvents.SmartContracts;
            block.Operations |= Operations.Migrations;

            var state = Cache.AppState.Get();
            state.MigrationOpsCount++;

            var statistics = await Cache.Statistics.GetAsync(state.Level);

            statistics.TotalCreated += contract.Balance;

            Db.MigrationOps.Add(migration);
            #endregion

            #region bigmaps
            var storageScript = new ContractStorage(micheStorage);
            var storageTree   = storageScript.Schema.ToTreeView(storageValue);
            var bigmaps       = storageTree.Nodes()
                                .Where(x => x.Schema is BigMapSchema)
                                .Select(x => (x, x.Schema as BigMapSchema, (int)(x.Value as MichelineInt).Value));

            foreach (var(bigmap, schema, ptr) in bigmaps)
            {
                block.Events |= BlockEvents.Bigmaps;

                migration.BigMapUpdates = (migration.BigMapUpdates ?? 0) + 1;
                Db.BigMapUpdates.Add(new BigMapUpdate
                {
                    Id          = Cache.AppState.NextBigMapUpdateId(),
                    Action      = BigMapAction.Allocate,
                    BigMapPtr   = ptr,
                    Level       = block.Level,
                    MigrationId = migration.Id
                });

                var allocated = new BigMap
                {
                    Id          = Cache.AppState.NextBigMapId(),
                    Ptr         = ptr,
                    ContractId  = contract.Id,
                    StoragePath = bigmap.Path,
                    KeyType     = schema.Key.ToMicheline().ToBytes(),
                    ValueType   = schema.Value.ToMicheline().ToBytes(),
                    Active      = true,
                    FirstLevel  = block.Level,
                    LastLevel   = block.Level,
                    ActiveKeys  = 0,
                    TotalKeys   = 0,
                    Updates     = 1,
                    Tags        = BigMaps.GetTags(bigmap)
                };
                Db.BigMaps.Add(allocated);

                if (address == LiquidityToken && allocated.StoragePath == "tokens")
                {
                    var rawKey   = new MichelineString(NullAddress.Address);
                    var rawValue = new MichelineInt(100);

                    allocated.ActiveKeys++;
                    allocated.TotalKeys++;
                    allocated.Updates++;
                    var key = new BigMapKey
                    {
                        Id         = Cache.AppState.NextBigMapKeyId(),
                        Active     = true,
                        BigMapPtr  = ptr,
                        FirstLevel = block.Level,
                        LastLevel  = block.Level,
                        JsonKey    = schema.Key.Humanize(rawKey),
                        JsonValue  = schema.Value.Humanize(rawValue),
                        RawKey     = schema.Key.Optimize(rawKey).ToBytes(),
                        RawValue   = schema.Value.Optimize(rawValue).ToBytes(),
                        KeyHash    = schema.GetKeyHash(rawKey),
                        Updates    = 1
                    };
                    Db.BigMapKeys.Add(key);

                    migration.BigMapUpdates++;
                    Db.BigMapUpdates.Add(new BigMapUpdate
                    {
                        Id          = Cache.AppState.NextBigMapUpdateId(),
                        Action      = BigMapAction.AddKey,
                        BigMapKeyId = key.Id,
                        BigMapPtr   = key.BigMapPtr,
                        JsonValue   = key.JsonValue,
                        RawValue    = key.RawValue,
                        Level       = key.LastLevel,
                        MigrationId = migration.Id
                    });
                }
            }
            #endregion
        }
Esempio n. 10
0
 private void Generate(
     Action <ModelBuilder> buildAction,
     MigrationOperation operation,
     CharSetBehavior charSetBehavior,
     CharSet charSet)
 => Generate(buildAction, new[] { operation }, default, charSetBehavior, charSet);
Esempio n. 11
0
        private static SqlStatement Generate(MigrationOperation migrationOperation)
        {
            var sqlGenerator = new SqlServerMigrationOperationSqlGenerator(new SqlServerTypeMapper());

            return(sqlGenerator.Generate(new[] { migrationOperation }).Single());
        }
Esempio n. 12
0
        private static string Generate(MigrationOperation migrationOperation, IModel targetModel = null)
        {
            var batches = SqlGenerator(targetModel).Generate(migrationOperation);

            return(string.Join(Environment.NewLine, batches.Select(b => b.Sql)));
        }
Esempio n. 13
0
 protected override void VisitDefault(MigrationOperation sqlOperation, DatabaseModel databaseModel)
 {
 }
        private static SqlStatement Generate(MigrationOperation migrationOperation, bool generateIdempotentSql)
        {
            var sqlGenerator = new MigrationOperationSqlGenerator(new RelationalTypeMapper());

            return(sqlGenerator.Generate(new[] { migrationOperation }, generateIdempotentSql).Single());
        }
 protected virtual void IndexTraits(
     [NotNull] MigrationOperation operation,
     [CanBeNull] IModel model,
     [NotNull] RelationalCommandListBuilder builder)
 {
 }
Esempio n. 16
0
 protected virtual void Generate(MigrationOperation operation)
 {
     Generate(_ => { }, new[] { operation });
 }
        private string GenerateSqlStatement(MigrationOperation migrationOperation)
        {
            dynamic concreteMigrationOperation = migrationOperation;

            return(GenerateSqlStatementConcrete(concreteMigrationOperation));
        }
 private static SqlStatement Generate(MigrationOperation migrationOperation, DatabaseModel database = null)
 {
     return(CreateSqlGenerator(database).Generate(new[] { migrationOperation }).Single());
 }
 private string GenerateSqlStatementConcrete(MigrationOperation migrationOperation)
 {
     Debug.Assert(false);
     return(string.Empty);
 }
        public virtual void AddOperation([NotNull] MigrationOperation operation)
        {
            Check.NotNull(operation, "operation");

            _operations.Add(operation);
        }
 private static string Generate(MigrationOperation operation, DatabaseModel database = null)
 {
     return(CreateGenerator().Generate(operation).Sql);
 }
        /// <summary>
        /// Generates SQL for a <see cref="MigrationOperation" />.
        /// Allows derived providers to handle additional operation types.
        /// Generated SQL should be added using the Statement method.
        /// </summary>
        /// <param name="migrationOperation"> The operation to produce SQL for. </param>
        protected virtual void Generate(MigrationOperation migrationOperation)
        {
            Check.NotNull(migrationOperation, "migrationOperation");

            throw Error.SqlServerMigrationSqlGenerator_UnknownOperation(GetType().Name, migrationOperation.GetType().FullName);
        }
Esempio n. 23
0
        /// <summary>
        /// 添加索引的相关定义。
        /// </summary>
        /// <param name="operation">操作实例。</param>
        /// <param name="builder"><see cref="MigrationCommandListBuilder"/>实例。</param>
        /// <param name="isPrimaryKey">是否为主键。</param>
        protected override void IndexTraits(MigrationOperation operation, MigrationCommandListBuilder builder, bool isPrimaryKey = false)
        {
            var clustered = (operation[SqlServerAnnotationNames.Clustered] as bool?) ?? isPrimaryKey;

            builder.Append(clustered ? "CLUSTERED " : "NONCLUSTERED ");
        }
 private static SqlStatement Generate(MigrationOperation migrationOperation, DatabaseModel database = null)
 {
     return(CreateSqlGenerator(database).Generate(migrationOperation));
 }
Esempio n. 25
0
 private string Generate(MigrationOperation operation)
 {
     return(CreateGenerator().Generate(new[] { operation }).First().Sql);
 }