package bbolt

import (
	
	

	
)

// Check performs several consistency checks on the database for this transaction.
// An error is returned if any inconsistency is found.
//
// It can be safely run concurrently on a writable transaction. However, this
// incurs a high cost for large databases and databases with a lot of subbuckets
// because of caching. This overhead can be removed if running on a read-only
// transaction, however, it is not safe to execute other writer transactions at
// the same time.
//
// It also allows users to provide a customized `KVStringer` implementation,
// so that bolt can generate human-readable diagnostic messages.
func ( *Tx) ( ...CheckOption) <-chan error {
	 := checkConfig{
		kvStringer: HexKVStringer(),
	}
	for ,  := range  {
		(&)
	}

	 := make(chan error)
	go func() {
		// Close the channel to signal completion.
		defer close()
		.check(, )
	}()
	return 
}

func ( *Tx) ( checkConfig,  chan error) {
	defer func() {
		if  := recover();  != nil {
			 <- panicked{}
		}
	}()
	// Force loading free list if opened in ReadOnly mode.
	.db.loadFreelist()

	// Check if any pages are double freed.
	 := make(map[common.Pgid]bool)
	 := make([]common.Pgid, .db.freelist.Count())
	.db.freelist.Copyall()
	for ,  := range  {
		if [] {
			 <- fmt.Errorf("page %d: already freed", )
		}
		[] = true
	}

	// Track every reachable page.
	 := make(map[common.Pgid]*common.Page)
	[0] = .page(0) // meta0
	[1] = .page(1) // meta1
	if .meta.Freelist() != common.PgidNoFreelist {
		for  := uint32(0);  <= .page(.meta.Freelist()).Overflow(); ++ {
			[.meta.Freelist()+common.Pgid()] = .page(.meta.Freelist())
		}
	}

	if .pageId == 0 {
		// Check the whole db file, starting from the root bucket and
		// recursively check all child buckets.
		.recursivelyCheckBucket(&.root, , , .kvStringer, )

		// Ensure all pages below high water mark are either reachable or freed.
		for  := common.Pgid(0);  < .meta.Pgid(); ++ {
			,  := []
			if ! && ![] {
				 <- fmt.Errorf("page %d: unreachable unfreed", int())
			}
		}
	} else {
		// Check the db file starting from a specified pageId.
		if .pageId < 2 || .pageId >= uint64(.meta.Pgid()) {
			 <- fmt.Errorf("page ID (%d) out of range [%d, %d)", .pageId, 2, .meta.Pgid())
			return
		}

		.recursivelyCheckPage(common.Pgid(.pageId), , , .kvStringer, )
	}
}

func ( *Tx) ( common.Pgid,  map[common.Pgid]*common.Page,  map[common.Pgid]bool,
	 KVStringer,  chan error) {
	.checkInvariantProperties(, , , , )
	.recursivelyCheckBucketInPage(, , , , )
}

func ( *Tx) ( common.Pgid,  map[common.Pgid]*common.Page,  map[common.Pgid]bool,
	 KVStringer,  chan error) {
	 := .page()

	switch {
	case .IsBranchPage():
		for  := range .BranchPageElements() {
			 := .BranchPageElement(uint16())
			.(.Pgid(), , , , )
		}
	case .IsLeafPage():
		for  := range .LeafPageElements() {
			 := .LeafPageElement(uint16())
			if .IsBucketEntry() {
				 := common.NewInBucket(, 0)
				 := Bucket{
					InBucket:    &,
					rootNode:    &node{isLeaf: .IsLeafPage()},
					FillPercent: DefaultFillPercent,
					tx:          ,
				}
				if  := .Bucket(.Key());  != nil {
					.recursivelyCheckBucket(, , , , )
				}
			}
		}
	default:
		 <- fmt.Errorf("unexpected page type (flags: %x) for pgId:%d", .Flags(), )
	}
}

func ( *Tx) ( *Bucket,  map[common.Pgid]*common.Page,  map[common.Pgid]bool,
	 KVStringer,  chan error) {
	// Ignore inline buckets.
	if .RootPage() == 0 {
		return
	}

	.checkInvariantProperties(.RootPage(), , , , )

	// Check each bucket within this bucket.
	_ = .ForEachBucket(func( []byte) error {
		if  := .Bucket();  != nil {
			.(, , , , )
		}
		return nil
	})
}

func ( *Tx) ( common.Pgid,  map[common.Pgid]*common.Page,  map[common.Pgid]bool,
	 KVStringer,  chan error) {
	.forEachPage(, func( *common.Page,  int,  []common.Pgid) {
		verifyPageReachable(, .meta.Pgid(), , , , )
	})

	.recursivelyCheckPageKeyOrder(, .KeyToString, )
}

func verifyPageReachable( *common.Page,  common.Pgid,  []common.Pgid,  map[common.Pgid]*common.Page,  map[common.Pgid]bool,  chan error) {
	if .Id() >  {
		 <- fmt.Errorf("page %d: out of bounds: %d (stack: %v)", int(.Id()), int(), )
	}

	// Ensure each page is only referenced once.
	for  := common.Pgid(0);  <= common.Pgid(.Overflow()); ++ {
		var  = .Id() + 
		if ,  := [];  {
			 <- fmt.Errorf("page %d: multiple references (stack: %v)", int(), )
		}
		[] = 
	}

	// We should only encounter un-freed leaf and branch pages.
	if [.Id()] {
		 <- fmt.Errorf("page %d: reachable freed", int(.Id()))
	} else if !.IsBranchPage() && !.IsLeafPage() {
		 <- fmt.Errorf("page %d: invalid type: %s (stack: %v)", int(.Id()), .Typ(), )
	}
}

// recursivelyCheckPageKeyOrder verifies database consistency with respect to b-tree
// key order constraints:
//   - keys on pages must be sorted
//   - keys on children pages are between 2 consecutive keys on the parent's branch page).
func ( *Tx) ( common.Pgid,  func([]byte) string,  chan error) {
	.recursivelyCheckPageKeyOrderInternal(, nil, nil, nil, , )
}

// recursivelyCheckPageKeyOrderInternal verifies that all keys in the subtree rooted at `pgid` are:
//   - >=`minKeyClosed` (can be nil)
//   - <`maxKeyOpen` (can be nil)
//   - Are in right ordering relationship to their parents.
//     `pagesStack` is expected to contain IDs of pages from the tree root to `pgid` for the clean debugging message.
func ( *Tx) (
	 common.Pgid, ,  []byte,  []common.Pgid,
	 func([]byte) string,  chan error) ( []byte) {

	 := .page()
	 = append(, )
	switch {
	case .IsBranchPage():
		// For branch page we navigate ranges of all subpages.
		 := 
		for  := range .BranchPageElements() {
			 := .BranchPageElement(uint16())
			verifyKeyOrder(.Pgid(), "branch", , .Key(), , , , , )

			 := 
			if  < len(.BranchPageElements())-1 {
				 = .BranchPageElement(uint16( + 1)).Key()
			}
			 = .(.Pgid(), .Key(), , , , )
			 = 
		}
		return 
	case .IsLeafPage():
		 := 
		for  := range .LeafPageElements() {
			 := .LeafPageElement(uint16())
			verifyKeyOrder(, "leaf", , .Key(), , , , , )
			 = .Key()
		}
		if .Count() > 0 {
			return .LeafPageElement(.Count() - 1).Key()
		}
	default:
		 <- fmt.Errorf("unexpected page type (flags: %x) for pgId:%d", .Flags(), )
	}
	return 
}

/***
 * verifyKeyOrder checks whether an entry with given #index on pgId (pageType: "branch|leaf") that has given "key",
 * is within range determined by (previousKey..maxKeyOpen) and reports found violations to the channel (ch).
 */
func verifyKeyOrder( common.Pgid,  string,  int,  []byte,  []byte,  []byte,  chan error,  func([]byte) string,  []common.Pgid) {
	if  == 0 &&  != nil && compareKeys(, ) > 0 {
		 <- fmt.Errorf("the first key[%d]=(hex)%s on %s page(%d) needs to be >= the key in the ancestor (%s). Stack: %v",
			, (), , , (), )
	}
	if  > 0 {
		 := compareKeys(, )
		if  > 0 {
			 <- fmt.Errorf("key[%d]=(hex)%s on %s page(%d) needs to be > (found <) than previous element (hex)%s. Stack: %v",
				, (), , , (), )
		}
		if  == 0 {
			 <- fmt.Errorf("key[%d]=(hex)%s on %s page(%d) needs to be > (found =) than previous element (hex)%s. Stack: %v",
				, (), , , (), )
		}
	}
	if  != nil && compareKeys(, ) >= 0 {
		 <- fmt.Errorf("key[%d]=(hex)%s on %s page(%d) needs to be < than key of the next element in ancestor (hex)%s. Pages stack: %v",
			, (), , , (), )
	}
}

// ===========================================================================================

type checkConfig struct {
	kvStringer KVStringer
	pageId     uint64
}

type CheckOption func(options *checkConfig)

func ( KVStringer) CheckOption {
	return func( *checkConfig) {
		.kvStringer = 
	}
}

// WithPageId sets a page ID from which the check command starts to check
func ( uint64) CheckOption {
	return func( *checkConfig) {
		.pageId = 
	}
}

// KVStringer allows to prepare human-readable diagnostic messages.
type KVStringer interface {
	KeyToString([]byte) string
	ValueToString([]byte) string
}

// HexKVStringer serializes both key & value to hex representation.
func () KVStringer {
	return hexKvStringer{}
}

type hexKvStringer struct{}

func (hexKvStringer) ( []byte) string {
	return hex.EncodeToString()
}

func (hexKvStringer) ( []byte) string {
	return hex.EncodeToString()
}