1// Copyright (c) 2015-2016 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package ffldb
6
7import (
8	"fmt"
9
10	"github.com/btcsuite/btcd/database"
11	"github.com/btcsuite/btcd/wire"
12	"github.com/btcsuite/btclog"
13)
14
15var log = btclog.Disabled
16
17const (
18	dbType = "ffldb"
19)
20
21// parseArgs parses the arguments from the database Open/Create methods.
22func parseArgs(funcName string, args ...interface{}) (string, wire.BitcoinNet, error) {
23	if len(args) != 2 {
24		return "", 0, fmt.Errorf("invalid arguments to %s.%s -- "+
25			"expected database path and block network", dbType,
26			funcName)
27	}
28
29	dbPath, ok := args[0].(string)
30	if !ok {
31		return "", 0, fmt.Errorf("first argument to %s.%s is invalid -- "+
32			"expected database path string", dbType, funcName)
33	}
34
35	network, ok := args[1].(wire.BitcoinNet)
36	if !ok {
37		return "", 0, fmt.Errorf("second argument to %s.%s is invalid -- "+
38			"expected block network", dbType, funcName)
39	}
40
41	return dbPath, network, nil
42}
43
44// openDBDriver is the callback provided during driver registration that opens
45// an existing database for use.
46func openDBDriver(args ...interface{}) (database.DB, error) {
47	dbPath, network, err := parseArgs("Open", args...)
48	if err != nil {
49		return nil, err
50	}
51
52	return openDB(dbPath, network, false)
53}
54
55// createDBDriver is the callback provided during driver registration that
56// creates, initializes, and opens a database for use.
57func createDBDriver(args ...interface{}) (database.DB, error) {
58	dbPath, network, err := parseArgs("Create", args...)
59	if err != nil {
60		return nil, err
61	}
62
63	return openDB(dbPath, network, true)
64}
65
66// useLogger is the callback provided during driver registration that sets the
67// current logger to the provided one.
68func useLogger(logger btclog.Logger) {
69	log = logger
70}
71
72func init() {
73	// Register the driver.
74	driver := database.Driver{
75		DbType:    dbType,
76		Create:    createDBDriver,
77		Open:      openDBDriver,
78		UseLogger: useLogger,
79	}
80	if err := database.RegisterDriver(driver); err != nil {
81		panic(fmt.Sprintf("Failed to regiser database driver '%s': %v",
82			dbType, err))
83	}
84}
85