All files / src/feed index.ts

97.61% Statements 82/84
78.12% Branches 25/32
100% Functions 13/13
97.61% Lines 82/84

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 25233x 33x 33x         33x 33x 33x               33x 33x 33x 33x                   33x   33x 33x 33x                           33x         9x 9x   2x       2x   7x 7x           33x               6x 6x   6x 6x 6x 6x   6x     33x               3x   3x   3x 1x 1x   1x                   2x                   33x 17x   17x     33x             4x 4x 4x 4x 4x   4x 4x 4x     4x           33x           2x 2x 2x   2x     33x   10x 8x 4x     4x   4x   4x             10x 5x 3x     2x     2x       2x   2x             10x 2x   2x 1x     2x   2x             10x                 33x 7x         6x     7x 3x     7x              
import { Binary, Optional, Types } from 'cafe-utility'
import { asContentAddressedChunk, Chunk } from '../chunk/cac'
import {
  makeSingleOwnerChunkFromData,
  uploadSingleOwnerChunkData,
  uploadSingleOwnerChunkWithWrappedChunk,
} from '../chunk/soc'
import * as bytes from '../modules/bytes'
import * as chunkAPI from '../modules/chunk'
import {
  FeedPayloadResult,
  FeedReferenceResult,
  FeedUpdateOptions,
  fetchLatestFeedUpdate,
  probeFeed,
} from '../modules/feed'
import { BeeRequestOptions, FeedReader, FeedWriter, UploadOptions, UploadResult } from '../types'
import { Bytes } from '../utils/bytes'
import { BeeResponseError } from '../utils/error'
import { ResourceLocator } from '../utils/resource-locator'
import {
  BatchId,
  EthAddress,
  FeedIndex,
  Identifier,
  PrivateKey,
  Reference,
  Signature,
  Topic,
} from '../utils/typed-bytes'
import { makeFeedIdentifier } from './identifier'
 
const TIMESTAMP_PAYLOAD_OFFSET = 0
const TIMESTAMP_PAYLOAD_SIZE = 8
const REFERENCE_PAYLOAD_OFFSET = TIMESTAMP_PAYLOAD_SIZE
 
export interface Epoch {
  time: number
  level: number
}
 
export interface FeedUploadOptions extends UploadOptions, FeedUpdateOptions {}
 
export interface FeedUpdate {
  timestamp: Optional<number>
  payload: Bytes
}
 
export async function findNextIndex(
  requestOptions: BeeRequestOptions,
  owner: EthAddress,
  topic: Topic,
): Promise<FeedIndex> {
  try {
    const feedUpdate = await fetchLatestFeedUpdate(requestOptions, owner, topic)
 
    Iif (!feedUpdate.feedIndexNext) {
      throw Error('Feed index next is not defined. This should happen when fetching an exact index.')
    }
 
    return feedUpdate.feedIndexNext
  } catch (e) {
    if (e instanceof BeeResponseError) {
      return FeedIndex.fromBigInt(0n)
    }
    throw e
  }
}
 
export async function updateFeedWithReference(
  requestOptions: BeeRequestOptions,
  signer: PrivateKey,
  topic: Topic,
  reference: Reference | string | Uint8Array,
  postageBatchId: BatchId,
  options?: FeedUploadOptions,
): Promise<UploadResult> {
  reference = new Reference(reference)
  const nextIndex = options?.index ?? (await findNextIndex(requestOptions, signer.publicKey().address(), topic))
 
  const identifier = makeFeedIdentifier(topic, nextIndex)
  const at = options?.at ?? Date.now() / 1000.0
  const timestamp = Binary.numberToUint64(BigInt(Math.floor(at)), 'BE')
  const payloadBytes = Binary.concatBytes(timestamp, reference.toUint8Array())
 
  return uploadSingleOwnerChunkData(requestOptions, signer, postageBatchId, identifier, payloadBytes, options)
}
 
export async function updateFeedWithPayload(
  requestOptions: BeeRequestOptions,
  signer: PrivateKey,
  topic: Topic,
  data: Uint8Array | string,
  postageBatchId: BatchId,
  options?: FeedUploadOptions,
): Promise<UploadResult> {
  const nextIndex = options?.index ?? (await findNextIndex(requestOptions, signer.publicKey().address(), topic))
 
  const identifier = makeFeedIdentifier(topic, nextIndex)
 
  if (data.length > 4096) {
    const uploadResult = await bytes.upload(requestOptions, data, postageBatchId, options)
    const rootChunk = await chunkAPI.download(requestOptions, uploadResult.reference)
 
    return uploadSingleOwnerChunkWithWrappedChunk(
      requestOptions,
      signer,
      postageBatchId,
      identifier,
      rootChunk,
      options,
    )
  }
 
  return uploadSingleOwnerChunkData(
    requestOptions,
    signer,
    postageBatchId,
    identifier,
    Types.isString(data) ? Bytes.fromUtf8(data).toUint8Array() : data,
    options,
  )
}
 
export function getFeedUpdateChunkReference(owner: EthAddress, topic: Topic, index: FeedIndex): Reference {
  const identifier = makeFeedIdentifier(topic, index)
 
  return new Reference(Binary.keccak256(Binary.concatBytes(identifier.toUint8Array(), owner.toUint8Array())))
}
 
export async function downloadFeedUpdate(
  requestOptions: BeeRequestOptions,
  owner: EthAddress,
  topic: Topic,
  index: FeedIndex | number,
  hasTimestamp = false,
): Promise<FeedUpdate> {
  index = typeof index === 'number' ? FeedIndex.fromBigInt(BigInt(index)) : index
  const address = getFeedUpdateChunkReference(owner, topic, index)
  const data = await chunkAPI.download(requestOptions, address.toHex())
  const soc = makeSingleOwnerChunkFromData(data, address)
  let timestamp: Optional<number> = Optional.empty()
 
  if (hasTimestamp) {
    const timestampBytes = Bytes.fromSlice(soc.payload.toUint8Array(), TIMESTAMP_PAYLOAD_OFFSET, TIMESTAMP_PAYLOAD_SIZE)
    timestamp = Optional.of(Number(Binary.uint64ToNumber(timestampBytes.toUint8Array(), 'BE')))
  }
 
  return {
    timestamp,
    payload: new Bytes(soc.payload.offset(hasTimestamp ? REFERENCE_PAYLOAD_OFFSET : 0)),
  }
}
 
export async function downloadFeedUpdateAsCAC(
  requestOptions: BeeRequestOptions,
  owner: EthAddress,
  topic: Topic,
  index: FeedIndex | number,
): Promise<Chunk> {
  index = typeof index === 'number' ? FeedIndex.fromBigInt(BigInt(index)) : index
  const address = getFeedUpdateChunkReference(owner, topic, index)
  const data = await chunkAPI.download(requestOptions, address)
 
  return asContentAddressedChunk(data.slice(Identifier.LENGTH + Signature.LENGTH))
}
 
export function makeFeedReader(requestOptions: BeeRequestOptions, topic: Topic, owner: EthAddress): FeedReader {
  // TODO: remove after enough time has passed in deprecated version
  const download = async (options?: FeedUpdateOptions): Promise<FeedPayloadResult> => {
    if (options?.index === undefined) {
      return fetchLatestFeedUpdate(requestOptions, owner, topic)
    }
 
    const update = await downloadFeedUpdate(requestOptions, owner, topic, options.index, options.hasTimestamp ?? true)
 
    const feedIndex = typeof options.index === 'number' ? FeedIndex.fromBigInt(BigInt(options.index)) : options.index
 
    return {
      payload: update.payload,
      feedIndex,
      feedIndexNext: feedIndex.next(),
    }
  }
 
  const downloadPayload = async (options?: FeedUpdateOptions): Promise<FeedPayloadResult> => {
    if (options?.index === undefined) {
      return fetchLatestFeedUpdate(requestOptions, owner, topic)
    }
 
    const cac = await downloadFeedUpdateAsCAC(requestOptions, owner, topic, options.index)
 
    const payload =
      cac.span.toBigInt() <= 4096n
        ? cac.payload
        : await bytes.download(requestOptions, new ResourceLocator(cac.address))
 
    const feedIndex = typeof options.index === 'number' ? FeedIndex.fromBigInt(BigInt(options.index)) : options.index
 
    return {
      payload,
      feedIndex,
      feedIndexNext: feedIndex.next(),
    }
  }
 
  const downloadReference = async (options?: FeedUpdateOptions): Promise<FeedReferenceResult> => {
    let index = options?.index
 
    if (index === undefined) {
      index = (await probeFeed(requestOptions, owner, topic)).feedIndex
    }
 
    const payload = await download({ ...options, index: index })
 
    return {
      reference: new Reference(payload.payload.toUint8Array()),
      feedIndex: payload.feedIndex,
      feedIndexNext: payload.feedIndexNext ?? payload.feedIndex.next(),
    }
  }
 
  return {
    download,
    downloadPayload,
    downloadReference,
    owner,
    topic,
  }
}
 
export function makeFeedWriter(requestOptions: BeeRequestOptions, topic: Topic, signer: PrivateKey): FeedWriter {
  const upload = async (
    postageBatchId: BatchId,
    reference: Reference | string | Uint8Array,
    options?: FeedUploadOptions,
  ) => {
    return updateFeedWithReference(requestOptions, signer, topic, reference, postageBatchId, options)
  }
 
  const uploadPayload = async (postageBatchId: BatchId, data: Uint8Array | string, options?: FeedUploadOptions) => {
    return updateFeedWithPayload(requestOptions, signer, topic, data, postageBatchId, options)
  }
 
  return {
    ...makeFeedReader(requestOptions, topic, signer.publicKey().address()),
    upload,
    uploadReference: upload,
    uploadPayload,
  }
}