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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | import localforage from 'localforage'
 
import { BareNameFilter } from '../protocol/private/namefilter'
import { Branch, Links, Puttable, SimpleLink } from '../types'
import { AddResult, CID } from '../../ipfs'
import { Maybe } from '../../common'
import { Permissions } from '../../ucan/permissions'
import { SemVer } from '../semver'
import { sha256Str } from '../../keystore'
 
import * as identifiers from '../../common/identifiers'
import * as ipfs from '../../ipfs'
import * as keystore from '../../keystore'
import * as link from '../link'
import * as pathUtil from '../path'
import * as protocol from '../protocol'
import * as semver from '../semver'
import * as ucanPermissions from '../../ucan/permissions'
 
import BareTree from '../bare/tree'
import MMPT from '../protocol/private/mmpt'
import PublicTree from '../v1/PublicTree'
import PrivateTree from '../v1/PrivateTree'
 
 
export default class RootTree implements Puttable {
 
  links: Links
  mmpt: MMPT
  privateLog: Array<SimpleLink>
 
  publicTree: PublicTree
  prettyTree: BareTree
  privateTrees: Record<string, PrivateTree>
 
  constructor({ links, mmpt, privateLog, publicTree, prettyTree, privateTrees }: {
    links: Links,
    mmpt: MMPT,
    privateLog: Array<SimpleLink>,
 
    publicTree: PublicTree,
    prettyTree: BareTree,
    privateTrees: Record<string, PrivateTree>,
  }) {
    this.links = links
    this.mmpt = mmpt
    this.privateLog = privateLog
 
    this.publicTree = publicTree
    this.prettyTree = prettyTree
    this.privateTrees = privateTrees
  }
 
 
  // INITIALISATION
  // --------------
 
  static async empty({ rootKey }: { rootKey: string }): Promise<RootTree> {
    const publicTree = await PublicTree.empty()
    const prettyTree = await BareTree.empty()
    const mmpt = MMPT.create()
 
    // Private tree
    const rootTree = await PrivateTree.create(mmpt, rootKey, null)
    await rootTree.put()
 
    // Store root key
    const rootKeyId = await identifiers.readKey({ path: '/private' })
    const ks = await keystore.get()
    await ks.importSymmKey(rootKey, rootKeyId)
 
    // Construct tree
    const tree = new RootTree({
      links: {},
      mmpt,
      privateLog: [],
 
      publicTree,
      prettyTree,
      privateTrees: {
        '/': rootTree
      }
    })
 
    // Set version and store new sub trees
    tree.setVersion(semver.v1)
 
    await Promise.all([
      tree.updatePuttable(Branch.Public, publicTree),
      tree.updatePuttable(Branch.Pretty, prettyTree),
      tree.updatePuttable(Branch.Private, mmpt)
    ])
 
    // Fin
    return tree
  }
 
  static async fromCID({ cid, permissions }: { cid: CID, permissions?: Permissions }): Promise<RootTree> {
    const links = await protocol.basic.getLinks(cid)
    const keys = permissions ? await permissionKeys(permissions) : {}
 
    // Load public parts
    const publicCID = links[Branch.Public]?.cid || null
    const publicTree = publicCID === null
      ? await PublicTree.empty()
      : await PublicTree.fromCID(publicCID)
 
    const prettyTree = links[Branch.Pretty]
                         ? await BareTree.fromCID(links[Branch.Pretty].cid)
                         : await BareTree.empty()
 
    // Load private bits
    const privateCID = links[Branch.Private]?.cid || null
 
    let mmpt, privateTrees
    if (privateCID === null) {
      mmpt = await MMPT.create()
      privateTrees = {}
    } else {
      mmpt = await MMPT.fromCID(privateCID)
      privateTrees = await loadPrivateTrees(keys, mmpt)
    }
 
    const privateLogCid = links[Branch.PrivateLog]?.cid
    const privateLog = privateLogCid
      ? await ipfs.dagGet(privateLogCid)
          .then(dagNode => dagNode.Links.map(link.fromDAGLink))
          .then(links => links.sort((a, b) => {
            return parseInt(a.name, 10) - parseInt(b.name, 10)
          }))
      : []
 
    // Construct tree
    const tree = new RootTree({
      links,
      mmpt,
      privateLog,
 
      publicTree,
      prettyTree,
      privateTrees
    })
 
    // Fin
    return tree
  }
 
 
  // MUTATIONS
  // ---------
 
  async put(): Promise<CID> {
    const { cid } = await this.putDetailed()
    return cid
  }
 
  async putDetailed(): Promise<AddResult> {
    return protocol.basic.putLinks(this.links)
  }
 
  updateLink(name: string, result: AddResult): this {
    const { cid, size, isFile } = result
    this.links[name] = link.make(name, cid, isFile, size)
    return this
  }
 
  async updatePuttable(name: string, puttable: Puttable): Promise<this> {
    return this.updateLink(name, await puttable.putDetailed())
  }
 
 
  // PRIVATE TREES
  // -------------
 
  findPrivateTree(path: string[]): [string, PrivateTree | null] {
    return findPrivateTree(this.privateTrees, path)
  }
 
 
  // PRIVATE LOG
  // -----------
  // CBOR array containing chunks.
  //
  // Chunk size is based on the default IPFS block size,
  // which is 1024 * 256 bytes. 1 log chunk should fit in 1 block.
  // We'll use the CSV format for the data in the chunks.
  static LOG_CHUNK_SIZE = 1020 // Math.floor((1024 * 256) / (256 + 1))
 
 
  async addPrivateLogEntry(cid: string): Promise<void> {
    const log = [...this.privateLog]
    let idx = Math.max(0, log.length - 1)
 
    // get last chunk
    let lastChunk = log[idx]?.cid
      ? (await ipfs.cat(log[idx].cid)).split(",")
      : []
 
    // needs new chunk
    const needsNewChunk = lastChunk.length + 1 > RootTree.LOG_CHUNK_SIZE
    if (needsNewChunk) {
      idx = idx + 1
      lastChunk = []
    }
 
    // add to chunk
    const hashedCid = await sha256Str(cid)
    const updatedChunk = [...lastChunk, hashedCid]
    const updatedChunkDeposit = await protocol.basic.putFile(
      updatedChunk.join(",")
    )
 
    log[idx] = {
      name: idx.toString(),
      cid: updatedChunkDeposit.cid,
      size: updatedChunkDeposit.size
    }
 
    // save log
    const logDeposit = await ipfs.dagPutLinks(
      log.map(link.toDAGLink)
    )
 
    this.updateLink(Branch.PrivateLog, {
      cid: logDeposit.cid,
      isFile: false,
      size: await ipfs.size(logDeposit.cid)
    })
 
    this.privateLog = log
  }
 
 
  // VERSION
  // -------
 
  async setVersion(version: SemVer): Promise<this> {
    const result = await protocol.basic.putFile(semver.toString(version))
    return this.updateLink(Branch.Version, result)
  }
 
}
 
 
 
// ㊙️
 
 
async function findBareNameFilter(
  map: Record<string, PrivateTree>,
  privatePathWithLeadingSlash: string
): Promise<Maybe<BareNameFilter>> {
  const privatePath = privatePathWithLeadingSlash.slice(1)
  const bareNameFilterId = await identifiers.bareNameFilter({ path: "/private/" + privatePath })
  const bareNameFilter: Maybe<BareNameFilter> = await localforage.getItem(bareNameFilterId)
  if (bareNameFilter) return bareNameFilter
 
  const pathParts = pathUtil.splitParts(privatePath)
  const [treePath, tree] = findPrivateTree(map, pathParts)
  if (!tree) return null
 
  const relativePath = privatePath.replace(new RegExp("^" + treePath), "")
  if (!tree.exists(relativePath)) await tree.mkdir(relativePath)
  return tree.get(relativePath).then(t => t ? t.header.bareNameFilter : null)
}
 
function findPrivateTree(
  map: Record<string, PrivateTree>,
  path: string[]
): [string, PrivateTree | null] {
  const fullPath = pathUtil.join(path)
  const t = map['/' + fullPath]
  if (t) return [ fullPath, t ]
 
  return path.length > 0
    ? findPrivateTree(map, path.slice(0, -1))
    : [ fullPath, null ]
}
 
function loadPrivateTrees(
  keys: Record<string, string>,
  mmpt: MMPT
): Promise<Record<string, PrivateTree>> {
  return sortedKeys(keys).reduce((acc, [path, key]) => {
    return acc.then(async map => {
      const prop = removePrivatePrefixAndLaggingSlash(path)
 
      let privateTree
 
      // if root, no need for bare name filter
      if (prop === "/" || prop === "") {
        privateTree = await PrivateTree.fromBaseKey(mmpt, key)
 
      } else {
        const bareNameFilter = await findBareNameFilter(map, prop)
        if (!bareNameFilter) throw new Error(`Was trying to load the PrivateTree for the path \`${path}\`, but couldn't find the bare name filter for it.`)
 
        privateTree = await PrivateTree.fromBareNameFilter(mmpt, bareNameFilter, key)
 
      }
 
      return { ...map, [prop]: privateTree }
    })
  }, Promise.resolve({}))
}
 
async function permissionKeys(
  permissions: Permissions
): Promise<Record<string, string>> {
  return ucanPermissions.paths(permissions).reduce(async (acc, p) => {
    if (p.startsWith('/public')) return acc
    const name = await identifiers.readKey({ path: p })
    return acc.then(async map => ({ ...map, [p]: (await keystore.getKeyByName(name)) }))
  }, Promise.resolve({}))
}
 
function removePrivatePrefixAndLaggingSlash(path: string): string {
  return '/' + path
    .replace(/^\/?private(\/|$)/, "")
    .replace(/^\/+/, "")
    .replace(/\/+$/, "")
}
 
/**
 * Sort keys alphabetically.
 * This is used to sort paths by parent first.
 */
function sortedKeys(keys: Record<string, string>): Array<[string, string]> {
  return Object.entries(keys).sort(
    (a, b) => a[0].localeCompare(b[0])
  )
}
  |