Skip to content

Services (δ)

Bases: StateComponent

Source code in pyjamaz/state/components.py
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
class Services(StateComponent):
    component_id = 255

    def validate_extrinsic_preimages(
            self,
            extrinsic_preimages: List[Preimage],
            pre_state_services: ServicesState,
    ):
        """
        Validate quality of extrinsic preimages.
        TODO Emiel: check if pre_state_services is correct, should be after accumulate?

        Parameters
        ----------
        extrinsic_preimages
        pre_state_services

        Returns
        -------

        """
        if len(extrinsic_preimages) > 0:
            if not self.are_preimages_unique(extrinsic_preimages):
                raise StateTransitionError(ServicesErrorCode.preimages_not_sorted_unique)

            if not self.are_preimages_sorted(extrinsic_preimages):
                raise StateTransitionError(ServicesErrorCode.preimages_not_sorted_unique)

            # GP-0.7.2-eq:12.37
            for preimage in extrinsic_preimages:
                if not pre_state_services.is_preimage_needed(preimage):
                    raise StateTransitionError(ServicesErrorCode.preimage_unneeded)

    @staticmethod
    def are_preimages_unique(preimages: List[Preimage]) -> bool:
        """
        GP-0.7.2-eq:12.36 | Are all preimages unique?

        Parameters
        ----------
        preimages: List[Preimage]

        Returns
        -------
        bool
        """
        return len(preimages) == len({(p.requester, p.blob) for p in preimages})

    @staticmethod
    def are_preimages_sorted(preimages: List[Preimage]) -> bool:
        """
        GP-0.7.2-eq:12.36 | Are all preimages sorted?

        Parameters
        ----------
        preimages: List[Preimage]

        Returns
        -------
        bool
        """

        sorted_preimage = lambda p: p.sort_key()

        return all(
            sorted_preimage(preimages[i]) <= sorted_preimage(preimages[i + 1]) for i in range(len(preimages) - 1)
        )

    @log_execution_time
    async def state_transition_after_preimages(
            self,
            extrinsic_preimages: List[Preimage],
            intermediate_state_after_accumulation: ServicesState,
            post_state_timeslot: TimeslotState
    ) -> ServicesAfterPreimagesOutput:
        """
        GP-0.7.2-eq:12.38 (δ') | Final state transition function after processing Preimages for the state's
        services.

        Parameters
        ----------
        extrinsic_preimages: List[Preimage]
            GP-0.7.2-eq:4.18 (bold_E_P)
        intermediate_state_after_accumulation: ServicesState
            GP-0.7.2-eq:4.18 (δ‡)
        post_state_timeslot: TimeslotState
            GP-0.7.2-eq:4.18 (τ')

        Returns
        -------
        ServicesAfterPreimagesOutput
            Output containing: Intermediate state after processing Preimages of ServicesState (δ†)
        """

        # GP-0.7.2-eq:12.37
        for preimage in extrinsic_preimages:

            preimage_hash = blake2b_256_hash(preimage.blob)
            preimage_length = len(preimage.blob)

            pre_image_exists = intermediate_state_after_accumulation.preimage_exists(preimage.requester, preimage_hash)
            try:
                is_newly_requested = intermediate_state_after_accumulation.retrieve_preimage_availability(
                    preimage.requester, preimage_hash, preimage_length
                ) == []
            except StateKeyNoResult:
                is_newly_requested = False

            # check if preimage does not already exist and is newly requested
            if not pre_image_exists and is_newly_requested:

                # Store preimage
                intermediate_state_after_accumulation.store_preimage(
                    service_account_id=preimage.requester,
                    preimage_blob=preimage.blob,
                    save_to_tx=True
                )

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(topic=MESSAGE_TYPES.PREIMAGE, data=[preimage.requester, preimage_hash, preimage.blob])
                    )

                # Update availability information
                intermediate_state_after_accumulation.store_preimage_availability(
                    service_account_id=preimage.requester,
                    preimage_hash=preimage_hash,
                    preimage_length=preimage_length,
                    value=[post_state_timeslot.number],
                    save_to_tx=True
                )

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(
                            topic=MESSAGE_TYPES.PREIMAGE_AVAILABILITY,
                            data=[preimage.requester, preimage_hash, preimage_length, [post_state_timeslot.number]]
                        )
                    )

        return ServicesAfterPreimagesOutput(
            post_state=intermediate_state_after_accumulation
        )

    @log_execution_time
    async def state_transition_accumulation(
            self,
            accumulatable_work_reports: List[WorkReport],
            pre_state_privileged_services: PrivilegedServicesState,
            pre_state_services: ServicesState,
            pre_state_validator_queue: ValidatorQueueState,
            pre_state_authorizer_queues: AuthorizerQueuesState,
            post_state_timeslot: TimeslotState,
            post_state_entropy: EntropyState,
    ) -> ServicesAfterAccumulationOutput:
        """
        GP-0.7.2-eq:12.27 (δ†) | State transition function for the state's services.

        Parameters
        ----------
        accumulatable_work_reports: List[WorkReport]
            GP-0.7.2-eq:4.16 (R*)
        pre_state_services: ServicesState
            GP-0.7.2-eq:4.16 (δ)
        pre_state_privileged_services: PrivilegedServicesState
            GP-0.7.2-eq:4.16 (χ)
        pre_state_validator_queue: ValidatorQueueState
            GP-0.7.2-eq:4.16 (ι)
        pre_state_authorizer_queues: AuthorizerQueuesState
            GP-0.7.2-eq:4.16 (𝜙)

        Returns
        -------
        ServicesAfterAccumulationOutput
            Output containing: intermediate state of ServicesState (δ†) and BeefyCommitmentMap (C).
        """

        services = deepcopy(pre_state_services)
        services.set_state_storage(self.app_context.state_storage)
        services.pending_changes = PendingChanges()

        accumulation_state = AccumulationStateComponents(
            services=services,
            validator_queue=deepcopy(pre_state_validator_queue),
            authorizer_queues=deepcopy(pre_state_authorizer_queues),
            privileged_services=deepcopy(pre_state_privileged_services)
        )

        # GP-0.7.2-eq:12.18
        gas_limit = max(
            gp_const.GAS_TOTAL, gp_const.GAS_ACCUMULATION * gp_const.CORE_COUNT + sum(
                pre_state_privileged_services.always_accumulators.values()
            )
        )

        DEBUG and logging.debug(f'ORDERED ACCUMULATION: W^*={[format_hash(w.package_spec.hash) for w in accumulatable_work_reports]}')

        # GP-0.7.2-eq:12.18
        output = await self.full_sequential_accumulation(
            gas_limit=gas_limit,
            deferred_transfers=[],
            work_reports=accumulatable_work_reports,
            accumulation_state=accumulation_state,
            auto_accumulate_services=pre_state_privileged_services.always_accumulators,
            post_state_timeslot=post_state_timeslot,
            post_state_entropy=post_state_entropy
        )

        # GP-0.7.2-eq:12.29
        self.block_context.set_accumulation_statistics(
            accumulation_gas_utilized=output.accumulation_gas_utilized,
            nr_work_results_accumulated=output.nr_work_results_accumulated,
        )

        # GP-0.7.2-eq:12.31 | Update last_accumulation_slot
        if self.block_context.accumulation_statistics is not None:
            for s in self.block_context.accumulation_statistics.keys():
                try:
                    service_account = output.post_accumulation_state.services.retrieve_service_account(s)
                    service_account.last_accumulation_slot = post_state_timeslot.number
                    output.post_accumulation_state.services.store_service_account(s, service_account, save_to_tx=True)
                except StateKeyNoResult:
                    pass

        # GP-0.6.0-eq:12.22
        return ServicesAfterAccumulationOutput(
            intermediate_state_after_accumulation=output.post_accumulation_state.services,
            post_state_privileged_services=output.post_accumulation_state.privileged_services,
            post_state_validator_queue=output.post_accumulation_state.validator_queue,
            post_state_authorizer_queues=output.post_accumulation_state.authorizer_queues,
            beefy_commitment_map=output.accumulation_commitment,
            nr_work_results_accumulated=output.nr_work_results_accumulated,
            accumulation_gas_utilized=output.accumulation_gas_utilized
        )

    async def full_sequential_accumulation(
            self,
            gas_limit: int,
            deferred_transfers: List[DeferredTransfer],
            work_reports: List[WorkReport],
            accumulation_state: AccumulationStateComponents,
            auto_accumulate_services: Dict[int, int],
            post_state_timeslot: TimeslotState,
            post_state_entropy: EntropyState
    ) -> FullAccumulationOutput:
        """
        GP-0.7.2-eq:12.18 ∆+ | full sequential accumulation function

        Parameters
        ----------
        gas_limit: int
        deferred_transfers: List[DeferredTransfer]
        work_reports: List[WorkReport]
        accumulation_state: AccumulationStateComponents
        auto_accumulate_services: Dict[int, int]
        post_state_timeslot: TimeslotState

        TODO how to deal with post_state_timeslot and post_state_entropy, not according to GP?

        Returns
        -------
        FullAccumulationOutput
        """

        gas_used = 0
        i = 0

        for i, work_report in enumerate(work_reports, start=1):
            gas_used += sum([r.accumulate_gas for r in work_report.results])
            if gas_used > gas_limit:
                i -= 1
                break

        n = len(deferred_transfers) + i + len(auto_accumulate_services)

        if n == 0:
            return FullAccumulationOutput(
                nr_work_results_accumulated=0,
                post_accumulation_state=accumulation_state,
                accumulation_commitment=BeefyCommitmentMap(),
                accumulation_gas_utilized={}
            )

        output = await self.parallel_accumulation(
            accumulation_state=accumulation_state,
            deferred_transfers=deferred_transfers,
            work_reports=work_reports[:i],
            auto_accumulate_services=auto_accumulate_services,
            post_state_timeslot=post_state_timeslot,
            post_state_entropy=post_state_entropy
        )

        gas_limit += sum([t.gas_limit for t in deferred_transfers])  # g*

        second_output = await self.full_sequential_accumulation(
            gas_limit=gas_limit - sum([u for u in output.accumulation_gas_utilized.values()]),
            deferred_transfers=output.deferred_transfers,
            work_reports=work_reports[i:],
            accumulation_state=output.accumulation_state,
            auto_accumulate_services={},
            post_state_timeslot=post_state_timeslot,
            post_state_entropy=post_state_entropy
        )

        output.accumulation_commitment.beefy_commitment_map.update(
            second_output.accumulation_commitment.beefy_commitment_map
            )

        # Update gas statistics
        output.accumulation_gas_utilized = sum_dict_values(
            output.accumulation_gas_utilized, second_output.accumulation_gas_utilized
        )

        return FullAccumulationOutput(
            nr_work_results_accumulated=i + second_output.nr_work_results_accumulated,
            post_accumulation_state=accumulation_state,
            accumulation_commitment=output.accumulation_commitment,
            accumulation_gas_utilized=output.accumulation_gas_utilized,
        )

    async def parallel_accumulation(
            self,
            accumulation_state: AccumulationStateComponents,
            deferred_transfers: List[DeferredTransfer],
            work_reports: List[WorkReport],
            auto_accumulate_services: Dict[int, int],
            post_state_timeslot: TimeslotState,
            post_state_entropy: EntropyState
    ) -> ParallelAccumulationOutput:
        """
        GP-0.7.2-eq:12.19 ∆* | parallel accumulation function

        Parameters
        ----------
        deferred_transfers: List[DeferredTransfer]
        accumulation_state: AccumulationStateComponents
        work_reports: List[WorkReport]
        auto_accumulate_services: Dict[int, int]
        post_state_timeslot: TimeslotState
        post_state_entropy: EntropyState

        Returns
        -------
        ParallelAccumulationOutput
        """
        # s (sorted!)
        service_ids = sorted(
            set(
                [r.service_id for w in work_reports for r in w.results] + list(auto_accumulate_services.keys()) +
                [t.receiver for t in deferred_transfers]
            )
        )

        # u
        accumulation_gas_utilized = {}
        # b
        beefy_commitment_map = BeefyCommitmentMap()

        DEBUG and logging.debug(f'Services to accumulate: {service_ids}')

        outputs = []

        pre_state_delegator = accumulation_state.privileged_services.delegator  # v
        pre_state_manager = accumulation_state.privileged_services.manager  # m
        pre_state_assigners = copy(accumulation_state.privileged_services.assigners)  # a
        pre_state_registrar = accumulation_state.privileged_services.registrar  # r

        manager_delegator = pre_state_delegator  # v*
        manager_assigners = copy(pre_state_assigners)  # a*
        manager_registrar = pre_state_registrar  # r*

        if USE_THREAD_POOL_ACCUMULATE:

            DEBUG and logging.debug(f'Using ThreadPool max_workers={THREAD_POOL_MAX_WORKERS}')

            with ThreadPoolExecutor(max_workers=THREAD_POOL_MAX_WORKERS) as tp:
                futs = {
                    tp.submit(
                        self.single_step_accumulation,
                        accumulation_state=accumulation_state,
                        deferred_transfers=deferred_transfers,
                        post_state_timeslot=post_state_timeslot,
                        post_state_entropy=post_state_entropy,
                        work_reports=work_reports,
                        auto_accumulate_services=auto_accumulate_services,
                        service_id=service_id,
                    ): service_id
                    for service_id in service_ids
                }

                for fut in as_completed(futs):
                    output = fut.result()
                    service_id = futs[fut]
                    outputs.append((service_id, output))

                # Sort output again on service ID (because of async processing)
                outputs.sort(key=lambda x: x[0])
        else:
            # Process services
            for service_id in service_ids:
                output = self.single_step_accumulation(
                    accumulation_state=accumulation_state,
                    deferred_transfers=deferred_transfers,
                    post_state_timeslot=post_state_timeslot,
                    post_state_entropy=post_state_entropy,
                    work_reports=work_reports,
                    auto_accumulate_services=auto_accumulate_services,
                    service_id=service_id
                )

                outputs.append((service_id, output))

        deferred_transfers = []

        deleted_service_ids = [] # bold_m
        updated_service_ids = []

        for service_id, output in outputs:
            # Update gas usage (u)
            accumulation_gas_utilized[service_id] = output.gas_used

            # Update transfers (t')
            deferred_transfers += output.deferred_transfers

            # GP-0.7.2-eq:12.21 Process provided pre-images
            for s, i in output.preimages:
                try:
                    availability = output.state_context.services.retrieve_preimage_availability(
                        s, blake2b_256_hash(i), len(i)
                        )
                except StateKeyNoResult:
                    # TODO check this
                    availability = None
                if availability == []:
                    output.state_context.services.store_preimage_availability(
                        s, blake2b_256_hash(i), len(i), [post_state_timeslot.number]
                    )
                    output.state_context.services.store_preimage(s, i)

            if output.accumulation_output is not None:
                beefy_commitment_map.add_accumulation_output(service_id, output.accumulation_output)  # b

            if service_id == pre_state_manager:
                # Process privilege services (m', a*, v*, z')
                accumulation_state.privileged_services.manager = output.state_context.privileged_services.manager  # m'
                accumulation_state.privileged_services.always_accumulators = output.state_context.privileged_services.always_accumulators  # z'
                manager_assigners = output.state_context.privileged_services.assigners  # a*
                manager_delegator = output.state_context.privileged_services.delegator  # v*
                manager_registrar = output.state_context.privileged_services.registrar  # r*

            # Process assigners (a')
            for c in range(CORE_COUNT):
                if service_id == accumulation_state.privileged_services.assigners[c]:
                    accumulation_state.privileged_services.assigners[c] = \
                    output.state_context.privileged_services.assigners[c]

            # Process delegator (v')
            if service_id == accumulation_state.privileged_services.delegator:
                accumulation_state.privileged_services.delegator = output.state_context.privileged_services.delegator  # v'

            # Process registrar (r')
            if service_id == accumulation_state.privileged_services.registrar:
                accumulation_state.privileged_services.registrar = output.state_context.privileged_services.registrar  # r'

            # Process validator queue (i')
            if service_id == pre_state_delegator:
                accumulation_state.validator_queue = output.state_context.validator_queue

            # Process authorizer queue (q')
            for c in range(CORE_COUNT):
                if service_id == pre_state_assigners[c]:
                    accumulation_state.authorizer_queues = output.state_context.authorizer_queues

            # Apply pending changes in services to global transaction (d')

            for (s_id, storage_hash), value in output.state_context.services.pending_changes.storage_items.items():
                if value is None:
                    output.state_context.services.delete_storage_item(s_id, storage_hash, save_to_tx=True)
                else:
                    output.state_context.services.store_storage_item(s_id, storage_hash, value, save_to_tx=True)

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(topic=MESSAGE_TYPES.STORAGE_ITEM, data=[service_id, storage_hash, value])
                    )

            for (s_id, preimage_hash), value in output.state_context.services.pending_changes.preimages.items():
                if value is None:
                    output.state_context.services.delete_preimage(s_id, preimage_hash, save_to_tx=True)
                else:
                    output.state_context.services.store_preimage(s_id, value, save_to_tx=True)

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(topic=MESSAGE_TYPES.PREIMAGE, data=[service_id, preimage_hash, value])
                    )

            for (s_id, preimage_hash,
                 preimage_length), value in output.state_context.services.pending_changes.preimages_availability.items():
                if value is None:
                    output.state_context.services.delete_preimage_availability(
                        s_id, preimage_hash, preimage_length, save_to_tx=True
                        )
                else:
                    output.state_context.services.store_preimage_availability(
                        s_id, preimage_hash, preimage_length, value, save_to_tx=True
                        )

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(
                            topic=MESSAGE_TYPES.PREIMAGE_AVAILABILITY,
                            data=[service_id, preimage_hash, preimage_length, value]
                        )
                    )

            for s_id, service_account in output.state_context.services.pending_changes.service_accounts.items():

                if service_account is None:
                    deleted_service_ids.append(s_id)
                else:
                    updated_service_ids.append((s_id, service_account))

            # Apply pending_changes to accumulation_state
            accumulation_state.services.add_pending_changes(output.state_context.services.pending_changes)

        # Apply pending deleted services
        for s_id in deleted_service_ids:
            accumulation_state.services.delete_service_account(s_id, save_to_tx=True)
            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(topic=MESSAGE_TYPES.SERVICE_ACCOUNT, data=[s_id, None])
                )

        # Apply pending service account changes
        for s_id, service_account in updated_service_ids:
            if s_id not in deleted_service_ids:
                accumulation_state.services.store_service_account(s_id, service_account, save_to_tx=True)

                if self.app_context.pubsub:
                    await self.app_context.pubsub.publish(
                        PubSubSignal(topic=MESSAGE_TYPES.SERVICE_ACCOUNT, data=[s_id, service_account])
                    )

        # Check if manager service modified a', v' and r' and then override
        for c in range(CORE_COUNT):
            if pre_state_assigners[c] != manager_assigners[c]:
                accumulation_state.privileged_services.assigners[c] = manager_assigners[c]

        if pre_state_delegator != manager_delegator:
            accumulation_state.privileged_services.delegator = manager_delegator

        if pre_state_registrar != manager_registrar:
            accumulation_state.privileged_services.registrar = manager_registrar

        return ParallelAccumulationOutput(
            accumulation_state=accumulation_state,
            deferred_transfers=deferred_transfers,
            accumulation_commitment=beefy_commitment_map,
            accumulation_gas_utilized=accumulation_gas_utilized
        )

    @staticmethod
    def single_step_accumulation(
            accumulation_state: AccumulationStateComponents,
            deferred_transfers: List[DeferredTransfer],
            post_state_timeslot: TimeslotState,
            post_state_entropy: EntropyState,
            work_reports: List[WorkReport],
            auto_accumulate_services: Dict[int, int],
            service_id: int
    ) -> 'PvmAccumulateOutput':
        """
        GP-0.7.2-eq:12.24 ∆1 | single step accumulation function

        Parameters
        ----------
        accumulation_state: AccumulationStateComponents
        deferred_transfers: List[DeferredTransfer]
        post_state_timeslot: TimeslotState
        post_state_entropy: EntropyState
        work_reports: List[WorkReport]
        auto_accumulate_services: Dict[int, int]
        service_id: int

        Returns
        -------
        PvmAccumulateOutput
        """
        # g = substitute_if_nothing(auto_accumulate_services.get(service_id), 0)
        g: int = auto_accumulate_services.get(service_id, 0)

        i: List[AccumulationInput] = []

        # Add deferred transfers (i^T)
        for t in deferred_transfers:
            if t.receiver == service_id:
                g += t.gas_limit

                i.append(AccumulationInput(deferred_transfer=t))

        # Add accumulation operands (i^U)
        for w in work_reports:
            for r in w.results:
                if r.service_id == service_id:
                    g += r.accumulate_gas

                    i.append(
                        AccumulationInput(
                            accumulation_operand=AccumulationOperand(
                                work_report_hash=w.package_spec.hash,
                                work_report_exports_root=w.package_spec.exports_root,
                                work_report_authorizer_hash=w.authorizer_hash,
                                work_report_auth_output=w.auth_output,
                                work_result_payload_hash=r.payload_hash,
                                work_result_gas_limit=r.accumulate_gas,
                                work_exec_result=r.result,
                            )
                        )
                    )

        state_context = deepcopy(accumulation_state)
        state_context.services.pending_changes = PendingChanges()

        return pvm_invoke_accumulate(
            state_context=state_context,
            timeslot=post_state_timeslot.number,
            service_id=service_id,
            gas_limit=g,
            accumulation_inputs=i,
            post_entropy=post_state_entropy
        )

    def retrieve_state(self) -> ServicesState:
        # State is retrieved per service
        return ServicesState(services={})

    async def store_state(self, state: ServicesState, transaction: Optional[Transaction] = None):
        """
        State for services are stored per service account

        Parameters
        ----------
        state
        transaction

        Returns
        -------

        """
        pass

validate_extrinsic_preimages(extrinsic_preimages: List[Preimage], pre_state_services: ServicesState)

Validate quality of extrinsic preimages. TODO Emiel: check if pre_state_services is correct, should be after accumulate?

Parameters:

Name Type Description Default
extrinsic_preimages List[Preimage]
required
pre_state_services ServicesState
required
Source code in pyjamaz/state/components.py
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
def validate_extrinsic_preimages(
        self,
        extrinsic_preimages: List[Preimage],
        pre_state_services: ServicesState,
):
    """
    Validate quality of extrinsic preimages.
    TODO Emiel: check if pre_state_services is correct, should be after accumulate?

    Parameters
    ----------
    extrinsic_preimages
    pre_state_services

    Returns
    -------

    """
    if len(extrinsic_preimages) > 0:
        if not self.are_preimages_unique(extrinsic_preimages):
            raise StateTransitionError(ServicesErrorCode.preimages_not_sorted_unique)

        if not self.are_preimages_sorted(extrinsic_preimages):
            raise StateTransitionError(ServicesErrorCode.preimages_not_sorted_unique)

        # GP-0.7.2-eq:12.37
        for preimage in extrinsic_preimages:
            if not pre_state_services.is_preimage_needed(preimage):
                raise StateTransitionError(ServicesErrorCode.preimage_unneeded)

are_preimages_unique(preimages: List[Preimage]) -> bool staticmethod

GP-0.7.2-eq:12.36 | Are all preimages unique?

Parameters:

Name Type Description Default
preimages List[Preimage]
required

Returns:

Type Description
bool
Source code in pyjamaz/state/components.py
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
@staticmethod
def are_preimages_unique(preimages: List[Preimage]) -> bool:
    """
    GP-0.7.2-eq:12.36 | Are all preimages unique?

    Parameters
    ----------
    preimages: List[Preimage]

    Returns
    -------
    bool
    """
    return len(preimages) == len({(p.requester, p.blob) for p in preimages})

are_preimages_sorted(preimages: List[Preimage]) -> bool staticmethod

GP-0.7.2-eq:12.36 | Are all preimages sorted?

Parameters:

Name Type Description Default
preimages List[Preimage]
required

Returns:

Type Description
bool
Source code in pyjamaz/state/components.py
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
@staticmethod
def are_preimages_sorted(preimages: List[Preimage]) -> bool:
    """
    GP-0.7.2-eq:12.36 | Are all preimages sorted?

    Parameters
    ----------
    preimages: List[Preimage]

    Returns
    -------
    bool
    """

    sorted_preimage = lambda p: p.sort_key()

    return all(
        sorted_preimage(preimages[i]) <= sorted_preimage(preimages[i + 1]) for i in range(len(preimages) - 1)
    )

state_transition_after_preimages(extrinsic_preimages: List[Preimage], intermediate_state_after_accumulation: ServicesState, post_state_timeslot: TimeslotState) -> ServicesAfterPreimagesOutput async

GP-0.7.2-eq:12.38 (δ') | Final state transition function after processing Preimages for the state's services.

Parameters:

Name Type Description Default
extrinsic_preimages List[Preimage]

GP-0.7.2-eq:4.18 (bold_E_P)

required
intermediate_state_after_accumulation ServicesState

GP-0.7.2-eq:4.18 (δ‡)

required
post_state_timeslot TimeslotState

GP-0.7.2-eq:4.18 (τ')

required

Returns:

Type Description
ServicesAfterPreimagesOutput

Output containing: Intermediate state after processing Preimages of ServicesState (δ†)

Source code in pyjamaz/state/components.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
@log_execution_time
async def state_transition_after_preimages(
        self,
        extrinsic_preimages: List[Preimage],
        intermediate_state_after_accumulation: ServicesState,
        post_state_timeslot: TimeslotState
) -> ServicesAfterPreimagesOutput:
    """
    GP-0.7.2-eq:12.38 (δ') | Final state transition function after processing Preimages for the state's
    services.

    Parameters
    ----------
    extrinsic_preimages: List[Preimage]
        GP-0.7.2-eq:4.18 (bold_E_P)
    intermediate_state_after_accumulation: ServicesState
        GP-0.7.2-eq:4.18 (δ‡)
    post_state_timeslot: TimeslotState
        GP-0.7.2-eq:4.18 (τ')

    Returns
    -------
    ServicesAfterPreimagesOutput
        Output containing: Intermediate state after processing Preimages of ServicesState (δ†)
    """

    # GP-0.7.2-eq:12.37
    for preimage in extrinsic_preimages:

        preimage_hash = blake2b_256_hash(preimage.blob)
        preimage_length = len(preimage.blob)

        pre_image_exists = intermediate_state_after_accumulation.preimage_exists(preimage.requester, preimage_hash)
        try:
            is_newly_requested = intermediate_state_after_accumulation.retrieve_preimage_availability(
                preimage.requester, preimage_hash, preimage_length
            ) == []
        except StateKeyNoResult:
            is_newly_requested = False

        # check if preimage does not already exist and is newly requested
        if not pre_image_exists and is_newly_requested:

            # Store preimage
            intermediate_state_after_accumulation.store_preimage(
                service_account_id=preimage.requester,
                preimage_blob=preimage.blob,
                save_to_tx=True
            )

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(topic=MESSAGE_TYPES.PREIMAGE, data=[preimage.requester, preimage_hash, preimage.blob])
                )

            # Update availability information
            intermediate_state_after_accumulation.store_preimage_availability(
                service_account_id=preimage.requester,
                preimage_hash=preimage_hash,
                preimage_length=preimage_length,
                value=[post_state_timeslot.number],
                save_to_tx=True
            )

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(
                        topic=MESSAGE_TYPES.PREIMAGE_AVAILABILITY,
                        data=[preimage.requester, preimage_hash, preimage_length, [post_state_timeslot.number]]
                    )
                )

    return ServicesAfterPreimagesOutput(
        post_state=intermediate_state_after_accumulation
    )

state_transition_accumulation(accumulatable_work_reports: List[WorkReport], pre_state_privileged_services: PrivilegedServicesState, pre_state_services: ServicesState, pre_state_validator_queue: ValidatorQueueState, pre_state_authorizer_queues: AuthorizerQueuesState, post_state_timeslot: TimeslotState, post_state_entropy: EntropyState) -> ServicesAfterAccumulationOutput async

GP-0.7.2-eq:12.27 (δ†) | State transition function for the state's services.

Parameters:

Name Type Description Default
accumulatable_work_reports List[WorkReport]

GP-0.7.2-eq:4.16 (R*)

required
pre_state_services ServicesState

GP-0.7.2-eq:4.16 (δ)

required
pre_state_privileged_services PrivilegedServicesState

GP-0.7.2-eq:4.16 (χ)

required
pre_state_validator_queue ValidatorQueueState

GP-0.7.2-eq:4.16 (ι)

required
pre_state_authorizer_queues AuthorizerQueuesState

GP-0.7.2-eq:4.16 (𝜙)

required

Returns:

Type Description
ServicesAfterAccumulationOutput

Output containing: intermediate state of ServicesState (δ†) and BeefyCommitmentMap (C).

Source code in pyjamaz/state/components.py
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
@log_execution_time
async def state_transition_accumulation(
        self,
        accumulatable_work_reports: List[WorkReport],
        pre_state_privileged_services: PrivilegedServicesState,
        pre_state_services: ServicesState,
        pre_state_validator_queue: ValidatorQueueState,
        pre_state_authorizer_queues: AuthorizerQueuesState,
        post_state_timeslot: TimeslotState,
        post_state_entropy: EntropyState,
) -> ServicesAfterAccumulationOutput:
    """
    GP-0.7.2-eq:12.27 (δ†) | State transition function for the state's services.

    Parameters
    ----------
    accumulatable_work_reports: List[WorkReport]
        GP-0.7.2-eq:4.16 (R*)
    pre_state_services: ServicesState
        GP-0.7.2-eq:4.16 (δ)
    pre_state_privileged_services: PrivilegedServicesState
        GP-0.7.2-eq:4.16 (χ)
    pre_state_validator_queue: ValidatorQueueState
        GP-0.7.2-eq:4.16 (ι)
    pre_state_authorizer_queues: AuthorizerQueuesState
        GP-0.7.2-eq:4.16 (𝜙)

    Returns
    -------
    ServicesAfterAccumulationOutput
        Output containing: intermediate state of ServicesState (δ†) and BeefyCommitmentMap (C).
    """

    services = deepcopy(pre_state_services)
    services.set_state_storage(self.app_context.state_storage)
    services.pending_changes = PendingChanges()

    accumulation_state = AccumulationStateComponents(
        services=services,
        validator_queue=deepcopy(pre_state_validator_queue),
        authorizer_queues=deepcopy(pre_state_authorizer_queues),
        privileged_services=deepcopy(pre_state_privileged_services)
    )

    # GP-0.7.2-eq:12.18
    gas_limit = max(
        gp_const.GAS_TOTAL, gp_const.GAS_ACCUMULATION * gp_const.CORE_COUNT + sum(
            pre_state_privileged_services.always_accumulators.values()
        )
    )

    DEBUG and logging.debug(f'ORDERED ACCUMULATION: W^*={[format_hash(w.package_spec.hash) for w in accumulatable_work_reports]}')

    # GP-0.7.2-eq:12.18
    output = await self.full_sequential_accumulation(
        gas_limit=gas_limit,
        deferred_transfers=[],
        work_reports=accumulatable_work_reports,
        accumulation_state=accumulation_state,
        auto_accumulate_services=pre_state_privileged_services.always_accumulators,
        post_state_timeslot=post_state_timeslot,
        post_state_entropy=post_state_entropy
    )

    # GP-0.7.2-eq:12.29
    self.block_context.set_accumulation_statistics(
        accumulation_gas_utilized=output.accumulation_gas_utilized,
        nr_work_results_accumulated=output.nr_work_results_accumulated,
    )

    # GP-0.7.2-eq:12.31 | Update last_accumulation_slot
    if self.block_context.accumulation_statistics is not None:
        for s in self.block_context.accumulation_statistics.keys():
            try:
                service_account = output.post_accumulation_state.services.retrieve_service_account(s)
                service_account.last_accumulation_slot = post_state_timeslot.number
                output.post_accumulation_state.services.store_service_account(s, service_account, save_to_tx=True)
            except StateKeyNoResult:
                pass

    # GP-0.6.0-eq:12.22
    return ServicesAfterAccumulationOutput(
        intermediate_state_after_accumulation=output.post_accumulation_state.services,
        post_state_privileged_services=output.post_accumulation_state.privileged_services,
        post_state_validator_queue=output.post_accumulation_state.validator_queue,
        post_state_authorizer_queues=output.post_accumulation_state.authorizer_queues,
        beefy_commitment_map=output.accumulation_commitment,
        nr_work_results_accumulated=output.nr_work_results_accumulated,
        accumulation_gas_utilized=output.accumulation_gas_utilized
    )

full_sequential_accumulation(gas_limit: int, deferred_transfers: List[DeferredTransfer], work_reports: List[WorkReport], accumulation_state: AccumulationStateComponents, auto_accumulate_services: Dict[int, int], post_state_timeslot: TimeslotState, post_state_entropy: EntropyState) -> FullAccumulationOutput async

GP-0.7.2-eq:12.18 ∆+ | full sequential accumulation function

Parameters:

Name Type Description Default
gas_limit int
required
deferred_transfers List[DeferredTransfer]
required
work_reports List[WorkReport]
required
accumulation_state AccumulationStateComponents
required
auto_accumulate_services Dict[int, int]
required
post_state_timeslot TimeslotState
required
TODO
required

Returns:

Type Description
FullAccumulationOutput
Source code in pyjamaz/state/components.py
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
async def full_sequential_accumulation(
        self,
        gas_limit: int,
        deferred_transfers: List[DeferredTransfer],
        work_reports: List[WorkReport],
        accumulation_state: AccumulationStateComponents,
        auto_accumulate_services: Dict[int, int],
        post_state_timeslot: TimeslotState,
        post_state_entropy: EntropyState
) -> FullAccumulationOutput:
    """
    GP-0.7.2-eq:12.18 ∆+ | full sequential accumulation function

    Parameters
    ----------
    gas_limit: int
    deferred_transfers: List[DeferredTransfer]
    work_reports: List[WorkReport]
    accumulation_state: AccumulationStateComponents
    auto_accumulate_services: Dict[int, int]
    post_state_timeslot: TimeslotState

    TODO how to deal with post_state_timeslot and post_state_entropy, not according to GP?

    Returns
    -------
    FullAccumulationOutput
    """

    gas_used = 0
    i = 0

    for i, work_report in enumerate(work_reports, start=1):
        gas_used += sum([r.accumulate_gas for r in work_report.results])
        if gas_used > gas_limit:
            i -= 1
            break

    n = len(deferred_transfers) + i + len(auto_accumulate_services)

    if n == 0:
        return FullAccumulationOutput(
            nr_work_results_accumulated=0,
            post_accumulation_state=accumulation_state,
            accumulation_commitment=BeefyCommitmentMap(),
            accumulation_gas_utilized={}
        )

    output = await self.parallel_accumulation(
        accumulation_state=accumulation_state,
        deferred_transfers=deferred_transfers,
        work_reports=work_reports[:i],
        auto_accumulate_services=auto_accumulate_services,
        post_state_timeslot=post_state_timeslot,
        post_state_entropy=post_state_entropy
    )

    gas_limit += sum([t.gas_limit for t in deferred_transfers])  # g*

    second_output = await self.full_sequential_accumulation(
        gas_limit=gas_limit - sum([u for u in output.accumulation_gas_utilized.values()]),
        deferred_transfers=output.deferred_transfers,
        work_reports=work_reports[i:],
        accumulation_state=output.accumulation_state,
        auto_accumulate_services={},
        post_state_timeslot=post_state_timeslot,
        post_state_entropy=post_state_entropy
    )

    output.accumulation_commitment.beefy_commitment_map.update(
        second_output.accumulation_commitment.beefy_commitment_map
        )

    # Update gas statistics
    output.accumulation_gas_utilized = sum_dict_values(
        output.accumulation_gas_utilized, second_output.accumulation_gas_utilized
    )

    return FullAccumulationOutput(
        nr_work_results_accumulated=i + second_output.nr_work_results_accumulated,
        post_accumulation_state=accumulation_state,
        accumulation_commitment=output.accumulation_commitment,
        accumulation_gas_utilized=output.accumulation_gas_utilized,
    )

parallel_accumulation(accumulation_state: AccumulationStateComponents, deferred_transfers: List[DeferredTransfer], work_reports: List[WorkReport], auto_accumulate_services: Dict[int, int], post_state_timeslot: TimeslotState, post_state_entropy: EntropyState) -> ParallelAccumulationOutput async

GP-0.7.2-eq:12.19 ∆* | parallel accumulation function

Parameters:

Name Type Description Default
deferred_transfers List[DeferredTransfer]
required
accumulation_state AccumulationStateComponents
required
work_reports List[WorkReport]
required
auto_accumulate_services Dict[int, int]
required
post_state_timeslot TimeslotState
required
post_state_entropy EntropyState
required

Returns:

Type Description
ParallelAccumulationOutput
Source code in pyjamaz/state/components.py
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
async def parallel_accumulation(
        self,
        accumulation_state: AccumulationStateComponents,
        deferred_transfers: List[DeferredTransfer],
        work_reports: List[WorkReport],
        auto_accumulate_services: Dict[int, int],
        post_state_timeslot: TimeslotState,
        post_state_entropy: EntropyState
) -> ParallelAccumulationOutput:
    """
    GP-0.7.2-eq:12.19 ∆* | parallel accumulation function

    Parameters
    ----------
    deferred_transfers: List[DeferredTransfer]
    accumulation_state: AccumulationStateComponents
    work_reports: List[WorkReport]
    auto_accumulate_services: Dict[int, int]
    post_state_timeslot: TimeslotState
    post_state_entropy: EntropyState

    Returns
    -------
    ParallelAccumulationOutput
    """
    # s (sorted!)
    service_ids = sorted(
        set(
            [r.service_id for w in work_reports for r in w.results] + list(auto_accumulate_services.keys()) +
            [t.receiver for t in deferred_transfers]
        )
    )

    # u
    accumulation_gas_utilized = {}
    # b
    beefy_commitment_map = BeefyCommitmentMap()

    DEBUG and logging.debug(f'Services to accumulate: {service_ids}')

    outputs = []

    pre_state_delegator = accumulation_state.privileged_services.delegator  # v
    pre_state_manager = accumulation_state.privileged_services.manager  # m
    pre_state_assigners = copy(accumulation_state.privileged_services.assigners)  # a
    pre_state_registrar = accumulation_state.privileged_services.registrar  # r

    manager_delegator = pre_state_delegator  # v*
    manager_assigners = copy(pre_state_assigners)  # a*
    manager_registrar = pre_state_registrar  # r*

    if USE_THREAD_POOL_ACCUMULATE:

        DEBUG and logging.debug(f'Using ThreadPool max_workers={THREAD_POOL_MAX_WORKERS}')

        with ThreadPoolExecutor(max_workers=THREAD_POOL_MAX_WORKERS) as tp:
            futs = {
                tp.submit(
                    self.single_step_accumulation,
                    accumulation_state=accumulation_state,
                    deferred_transfers=deferred_transfers,
                    post_state_timeslot=post_state_timeslot,
                    post_state_entropy=post_state_entropy,
                    work_reports=work_reports,
                    auto_accumulate_services=auto_accumulate_services,
                    service_id=service_id,
                ): service_id
                for service_id in service_ids
            }

            for fut in as_completed(futs):
                output = fut.result()
                service_id = futs[fut]
                outputs.append((service_id, output))

            # Sort output again on service ID (because of async processing)
            outputs.sort(key=lambda x: x[0])
    else:
        # Process services
        for service_id in service_ids:
            output = self.single_step_accumulation(
                accumulation_state=accumulation_state,
                deferred_transfers=deferred_transfers,
                post_state_timeslot=post_state_timeslot,
                post_state_entropy=post_state_entropy,
                work_reports=work_reports,
                auto_accumulate_services=auto_accumulate_services,
                service_id=service_id
            )

            outputs.append((service_id, output))

    deferred_transfers = []

    deleted_service_ids = [] # bold_m
    updated_service_ids = []

    for service_id, output in outputs:
        # Update gas usage (u)
        accumulation_gas_utilized[service_id] = output.gas_used

        # Update transfers (t')
        deferred_transfers += output.deferred_transfers

        # GP-0.7.2-eq:12.21 Process provided pre-images
        for s, i in output.preimages:
            try:
                availability = output.state_context.services.retrieve_preimage_availability(
                    s, blake2b_256_hash(i), len(i)
                    )
            except StateKeyNoResult:
                # TODO check this
                availability = None
            if availability == []:
                output.state_context.services.store_preimage_availability(
                    s, blake2b_256_hash(i), len(i), [post_state_timeslot.number]
                )
                output.state_context.services.store_preimage(s, i)

        if output.accumulation_output is not None:
            beefy_commitment_map.add_accumulation_output(service_id, output.accumulation_output)  # b

        if service_id == pre_state_manager:
            # Process privilege services (m', a*, v*, z')
            accumulation_state.privileged_services.manager = output.state_context.privileged_services.manager  # m'
            accumulation_state.privileged_services.always_accumulators = output.state_context.privileged_services.always_accumulators  # z'
            manager_assigners = output.state_context.privileged_services.assigners  # a*
            manager_delegator = output.state_context.privileged_services.delegator  # v*
            manager_registrar = output.state_context.privileged_services.registrar  # r*

        # Process assigners (a')
        for c in range(CORE_COUNT):
            if service_id == accumulation_state.privileged_services.assigners[c]:
                accumulation_state.privileged_services.assigners[c] = \
                output.state_context.privileged_services.assigners[c]

        # Process delegator (v')
        if service_id == accumulation_state.privileged_services.delegator:
            accumulation_state.privileged_services.delegator = output.state_context.privileged_services.delegator  # v'

        # Process registrar (r')
        if service_id == accumulation_state.privileged_services.registrar:
            accumulation_state.privileged_services.registrar = output.state_context.privileged_services.registrar  # r'

        # Process validator queue (i')
        if service_id == pre_state_delegator:
            accumulation_state.validator_queue = output.state_context.validator_queue

        # Process authorizer queue (q')
        for c in range(CORE_COUNT):
            if service_id == pre_state_assigners[c]:
                accumulation_state.authorizer_queues = output.state_context.authorizer_queues

        # Apply pending changes in services to global transaction (d')

        for (s_id, storage_hash), value in output.state_context.services.pending_changes.storage_items.items():
            if value is None:
                output.state_context.services.delete_storage_item(s_id, storage_hash, save_to_tx=True)
            else:
                output.state_context.services.store_storage_item(s_id, storage_hash, value, save_to_tx=True)

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(topic=MESSAGE_TYPES.STORAGE_ITEM, data=[service_id, storage_hash, value])
                )

        for (s_id, preimage_hash), value in output.state_context.services.pending_changes.preimages.items():
            if value is None:
                output.state_context.services.delete_preimage(s_id, preimage_hash, save_to_tx=True)
            else:
                output.state_context.services.store_preimage(s_id, value, save_to_tx=True)

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(topic=MESSAGE_TYPES.PREIMAGE, data=[service_id, preimage_hash, value])
                )

        for (s_id, preimage_hash,
             preimage_length), value in output.state_context.services.pending_changes.preimages_availability.items():
            if value is None:
                output.state_context.services.delete_preimage_availability(
                    s_id, preimage_hash, preimage_length, save_to_tx=True
                    )
            else:
                output.state_context.services.store_preimage_availability(
                    s_id, preimage_hash, preimage_length, value, save_to_tx=True
                    )

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(
                        topic=MESSAGE_TYPES.PREIMAGE_AVAILABILITY,
                        data=[service_id, preimage_hash, preimage_length, value]
                    )
                )

        for s_id, service_account in output.state_context.services.pending_changes.service_accounts.items():

            if service_account is None:
                deleted_service_ids.append(s_id)
            else:
                updated_service_ids.append((s_id, service_account))

        # Apply pending_changes to accumulation_state
        accumulation_state.services.add_pending_changes(output.state_context.services.pending_changes)

    # Apply pending deleted services
    for s_id in deleted_service_ids:
        accumulation_state.services.delete_service_account(s_id, save_to_tx=True)
        if self.app_context.pubsub:
            await self.app_context.pubsub.publish(
                PubSubSignal(topic=MESSAGE_TYPES.SERVICE_ACCOUNT, data=[s_id, None])
            )

    # Apply pending service account changes
    for s_id, service_account in updated_service_ids:
        if s_id not in deleted_service_ids:
            accumulation_state.services.store_service_account(s_id, service_account, save_to_tx=True)

            if self.app_context.pubsub:
                await self.app_context.pubsub.publish(
                    PubSubSignal(topic=MESSAGE_TYPES.SERVICE_ACCOUNT, data=[s_id, service_account])
                )

    # Check if manager service modified a', v' and r' and then override
    for c in range(CORE_COUNT):
        if pre_state_assigners[c] != manager_assigners[c]:
            accumulation_state.privileged_services.assigners[c] = manager_assigners[c]

    if pre_state_delegator != manager_delegator:
        accumulation_state.privileged_services.delegator = manager_delegator

    if pre_state_registrar != manager_registrar:
        accumulation_state.privileged_services.registrar = manager_registrar

    return ParallelAccumulationOutput(
        accumulation_state=accumulation_state,
        deferred_transfers=deferred_transfers,
        accumulation_commitment=beefy_commitment_map,
        accumulation_gas_utilized=accumulation_gas_utilized
    )

single_step_accumulation(accumulation_state: AccumulationStateComponents, deferred_transfers: List[DeferredTransfer], post_state_timeslot: TimeslotState, post_state_entropy: EntropyState, work_reports: List[WorkReport], auto_accumulate_services: Dict[int, int], service_id: int) -> PvmAccumulateOutput staticmethod

GP-0.7.2-eq:12.24 ∆1 | single step accumulation function

Parameters:

Name Type Description Default
accumulation_state AccumulationStateComponents
required
deferred_transfers List[DeferredTransfer]
required
post_state_timeslot TimeslotState
required
post_state_entropy EntropyState
required
work_reports List[WorkReport]
required
auto_accumulate_services Dict[int, int]
required
service_id int
required

Returns:

Type Description
PvmAccumulateOutput
Source code in pyjamaz/state/components.py
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
@staticmethod
def single_step_accumulation(
        accumulation_state: AccumulationStateComponents,
        deferred_transfers: List[DeferredTransfer],
        post_state_timeslot: TimeslotState,
        post_state_entropy: EntropyState,
        work_reports: List[WorkReport],
        auto_accumulate_services: Dict[int, int],
        service_id: int
) -> 'PvmAccumulateOutput':
    """
    GP-0.7.2-eq:12.24 ∆1 | single step accumulation function

    Parameters
    ----------
    accumulation_state: AccumulationStateComponents
    deferred_transfers: List[DeferredTransfer]
    post_state_timeslot: TimeslotState
    post_state_entropy: EntropyState
    work_reports: List[WorkReport]
    auto_accumulate_services: Dict[int, int]
    service_id: int

    Returns
    -------
    PvmAccumulateOutput
    """
    # g = substitute_if_nothing(auto_accumulate_services.get(service_id), 0)
    g: int = auto_accumulate_services.get(service_id, 0)

    i: List[AccumulationInput] = []

    # Add deferred transfers (i^T)
    for t in deferred_transfers:
        if t.receiver == service_id:
            g += t.gas_limit

            i.append(AccumulationInput(deferred_transfer=t))

    # Add accumulation operands (i^U)
    for w in work_reports:
        for r in w.results:
            if r.service_id == service_id:
                g += r.accumulate_gas

                i.append(
                    AccumulationInput(
                        accumulation_operand=AccumulationOperand(
                            work_report_hash=w.package_spec.hash,
                            work_report_exports_root=w.package_spec.exports_root,
                            work_report_authorizer_hash=w.authorizer_hash,
                            work_report_auth_output=w.auth_output,
                            work_result_payload_hash=r.payload_hash,
                            work_result_gas_limit=r.accumulate_gas,
                            work_exec_result=r.result,
                        )
                    )
                )

    state_context = deepcopy(accumulation_state)
    state_context.services.pending_changes = PendingChanges()

    return pvm_invoke_accumulate(
        state_context=state_context,
        timeslot=post_state_timeslot.number,
        service_id=service_id,
        gas_limit=g,
        accumulation_inputs=i,
        post_entropy=post_state_entropy
    )

store_state(state: ServicesState, transaction: Optional[Transaction] = None) async

State for services are stored per service account

Parameters:

Name Type Description Default
state ServicesState
required
transaction Optional[Transaction]
None
Source code in pyjamaz/state/components.py
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
async def store_state(self, state: ServicesState, transaction: Optional[Transaction] = None):
    """
    State for services are stored per service account

    Parameters
    ----------
    state
    transaction

    Returns
    -------

    """
    pass